<section class="w-full py-12 md:py-24 lg:py-32">
    <div class="container mx-auto px-4 md:px-6">
        <div class="mx-auto max-w-3xl">
            <div class="mb-8 space-y-2 text-center">
                <h1 class="font-headline text-3xl font-bold tracking-tight sm:text-4xl">
                    Upload Supporting Documents
                </h1>
                <p class="text-gray-500">
                    Upload required documents in PDF format for your bursary application.
                </p>
            </div>
            <% if (error) { %>
                <div class="mb-6 text-red-600 text-sm text-center"><%= error %></div>
                <% } %>
                <form id="upload-documents-form" class="space-y-8" enctype="multipart/form-data"  method="POST">
                    <div class="bg-white shadow-lg rounded-lg">
                        <div class="p-6 flex items-center space-x-2">
                            <i data-lucide="upload-cloud" class="h-6 w-6 text-blue-600"></i>
                            <h2 class="text-xl font-headline font-bold">Document Upload</h2>
                        </div>
                        <div class="p-6 pt-0 grid grid-cols-1 gap-6">
                            <div class="space-y-2">
                                <label for="applicationId" class="text-sm font-medium">Select Application</label>
                                <select
                                id="applicationId"
                                name="applicationId"
                                required
                                class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                                aria-describedby="applicationIdHelp"
                                >
                                <option value="">Select an application</option>
                            </select>
                            <p id="applicationIdHelp" class="text-xs text-gray-500">Choose the application to upload documents for.</p>
                        </div>
                        <div class="space-y-2">
                            <label for="type" class="text-sm font-medium">Document Type</label>
                            <select
                            id="type"
                            name="type"
                            required
                            class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                            aria-describedby="typeHelp"
                            >
                            <option value="">Select document type</option>
                            <option value="idDocument">Certified ID Document</option>
                            <option value="academicRecord">Latest Academic Record</option>
                            <option value="proofOfRegistration">Proof of Registration</option>
                        </select>
                        <p id="typeHelp" class="text-xs text-gray-500">Select the type of document you are uploading.</p>
                    </div>
                    <div class="space-y-2">
                        <label for="document" class="text-sm font-medium">Upload Document (PDF, max 5MB)</label>
                        <input
                        id="document"
                        name="document"
                        type="file"
                        accept="application/pdf"
                        required
                        class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
                        aria-describedby="documentHelp"
                        />
                        <p id="documentHelp" class="text-xs text-gray-500">Upload a PDF file, maximum size 5MB.</p>
                        <p id="fileName" class="text-xs text-gray-600 hidden"></p>
                    </div>
                </div>
            </div>
            <div class="flex justify-between items-center">
                <a
                href="/student/dashboard"
                class="inline-flex items-center bg-gray-200 text-gray-700 px-6 py-3 rounded-md hover:bg-gray-300 transition"
                aria-label="Back to dashboard"
                >
                <i data-lucide="arrow-left" class="h-4 w-4 mr-2"></i> Back
            </a>
            <button
            type="submit"
            class="bg-blue-600 text-white px-6 py-3 rounded-md hover:bg-blue-700 transition flex items-center"
            aria-label="Upload document"
            id="submit-btn"
            >
            <i data-lucide="upload" class="h-4 w-4 mr-2"></i> Upload Document
        </button>
    </div>
</form>
<div>
    <div id="loading" class="hidden text-center text-gray-600 mt-4">
        <i data-lucide="loader" class="text-blue-600 h-6 w-6 animate-spin inline-block"></i>
        Uploading document...
    </div>
</div>
</div>
</section>

<script nonce="<%= nonce %>">
    document.addEventListener('DOMContentLoaded', async () => {
        const form = document.getElementById('upload-documents-form');
        const applicationIdSelect = document.getElementById('applicationId');
        const documentInput = document.getElementById('document');
        const fileName = document.getElementById('fileName');
        const submitBtn = document.getElementById('submit-btn');
        const loading = document.getElementById('loading');

        async function fetchApplications() {
            try {
                const token = localStorage.getItem('jwtToken');
                if (!token) {
                    return Swal.fire({ icon: 'error', title: 'Not Authenticated', text: 'Please log in to continue.' });
                }

                const response = await api.get('/api/v1/applications');
                const applications = response.data.applications;

                if (!applications || !applications.length) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'No Applications',
                        text: 'No applications found. Please submit an application first.',
                        customClass: {
                            popup: 'bg-white rounded-lg shadow-lg',
                            title: 'text-gray-900 font-headline',
                            content: 'text-gray-600'
                        },
                        background: '#f9fafb',
                        iconColor: '#f59e0b'
                    }).then(() => {
                        applicationIdSelect.disabled = true;
                        submitBtn.disabled = true;
                    });
                    return;
                }

                applications.forEach(application => {
                    const option = document.createElement('option');
                    option.value = application.id;
                    option.textContent = `${application.refNumber} - ${application.status || 'Unknown'}`;
                    applicationIdSelect.appendChild(option);
                });
            } catch (err) {
                console.error('Error fetching applications:', err);
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: err.response?.data?.message || 'Unable to load applications.',
                    customClass: {
                        popup: 'bg-white rounded-lg shadow-lg',
                        title: 'text-gray-900 font-headline',
                        content: 'text-gray-600'
                    },
                    background: '#f9fafb',
                    iconColor: '#dc2626'
                });
            }
        }

        fetchApplications();

        documentInput.addEventListener('change', () => {
            if (documentInput.files.length > 0) {
                fileName.textContent = `Selected file: ${documentInput.files[0].name}`;
                fileName.classList.remove('hidden');
            } else {
                fileName.textContent = '';
                fileName.classList.add('hidden');
            }
        });

        form.addEventListener('submit', async (event) => {
            event.preventDefault();
            submitBtn.disabled = true;
            loading.classList.remove('hidden');

            const formData = new FormData(form);
            const applicationId = formData.get('applicationId');
            const type = document.getElementById('type').value;
            const documentFile = formData.get('document');

            if (!applicationId || !type || !documentFile) {
                Swal.fire({
                    icon: 'error',
                    title: 'Missing Fields',
                    text: 'All fields must be filled, and a PDF file must be uploaded.',
                    customClass: {
                        popup: 'bg-white rounded-lg shadow-lg',
                        title: 'text-gray-900 font-headline',
                        content: 'text-gray-600'
                    },
                    background: '#f9fafb',
                    iconColor: '#dc2626'
                });
                submitBtn.disabled = false;
                loading.classList.add('hidden');
                return;
            }

            if (documentFile.type !== 'application/pdf') {
                Swal.fire({
                    icon: 'error',
                    title: 'Invalid File',
                    text: 'Only PDF files are allowed.',
                    customClass: {
                        popup: 'bg-white rounded-lg shadow-lg',
                        title: 'text-gray-900 font-headline',
                        content: 'text-gray-600'
                    },
                    background: '#f9fafb',
                    iconColor: '#dc2626'
                });
                submitBtn.disabled = false;
                loading.classList.add('hidden');
                return;
            }

            if (documentFile.size > 5 * 1024 * 1024) {
                Swal.fire({
                    icon: 'error',
                    title: 'File Too Large',
                    text: 'File size must not exceed 5MB.',
                    customClass: {
                        popup: 'bg-white rounded-lg shadow-lg',
                        title: 'text-gray-900 font-headline',
                        content: 'text-gray-600'
                    },
                    background: '#f9fafb',
                    iconColor: '#dc2626'
                });
                submitBtn.disabled = false;
                loading.classList.add('hidden');
                return;
            }

            try {
                const token = localStorage.getItem('jwtToken');
                if (!token) {
                    return Swal.fire({ icon: 'error', title: 'Not Authenticated', text: 'Please log in to continue.' });
                }

                const response = await api.post('/api/v1/documents/upload', formData,  {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                });

                Swal.fire({
                    icon: 'success',
                    title: 'Document Uploaded',
                    text: 'Your document has been uploaded successfully.',
                    timer: 2000,
                    showConfirmButton: false,
                    customClass: {
                        popup: 'bg-white rounded-lg shadow-lg',
                        title: 'text-gray-900 font-headline',
                        content: 'text-gray-600'
                    },
                    background: '#f9fafb',
                    iconColor: '#2563eb'
                }).then(() => {
                    window.location.href = '/student/dashboard';
                });
            } catch (err) {
                console.error('Error uploading document:', err);
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: err.response?.data?.message || 'An error occurred while uploading your document.',
                    customClass: {
                        popup: 'bg-white rounded-lg shadow-lg',
                        title: 'text-gray-900 font-headline',
                        content: 'text-gray-600'
                    },
                    background: '#f9fafb',
                    iconColor: '#dc2626'
                });
            } finally {
                submitBtn.disabled = false;
                loading.classList.add('hidden');
            }
        });

        lucide.createIcons();
    });
</script>
