document.addEventListener('DOMContentLoaded', () => {
    initNavigation();
    initModal();
    loadDashboardStats();
    loadDistricts();
    loadStudents();

    // Create District Button
    document.getElementById('createDistrictBtn').addEventListener('click', async () => {
        const name = document.getElementById('newDistrictName').value;
        if (!name) return alert('Enter district name');
        
        try {
            const res = await fetch('/api/districts', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ name })
            });
            if (res.ok) {
                document.getElementById('newDistrictName').value = '';
                loadDistricts();
            } else {
                alert('Error creating district');
            }
        } catch (err) {
            console.error(err);
        }
    });

    // Upload Form Submit
    document.getElementById('uploadForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        const districtId = document.getElementById('uploadDistrictId').value;
        const fileInput = document.getElementById('fileInput');
        const statusDiv = document.getElementById('uploadStatus');

        if (!fileInput.files.length) return alert('Please select a file');

        const formData = new FormData();
        formData.append('district_id', districtId);
        
        let testType = document.getElementById('uploadTestType').value;
        const testNum = document.getElementById('uploadTestNumber').value;
        if (testNum) {
            testType += ` ${testNum}`;
        }
        
        formData.append('test_type', testType);
        formData.append('file', fileInput.files[0]);

        const btn = document.getElementById('submitUploadBtn');
        btn.disabled = true;
        btn.innerText = 'Uploading...';
        statusDiv.innerText = '';
        statusDiv.style.color = 'inherit';

        try {
            const res = await fetch('/api/upload-marks', {
                method: 'POST',
                body: formData
            });
            const data = await res.json();
            
            if (res.ok) {
                statusDiv.innerText = data.message;
                statusDiv.style.color = '#10b981'; // green
                fileInput.value = '';
                setTimeout(() => {
                    document.getElementById('uploadModal').classList.remove('active');
                    loadDashboardStats();
                    loadDistricts();
                    loadStudents();
                }, 2000);
            } else {
                statusDiv.innerText = 'Error: ' + data.error;
                statusDiv.style.color = '#ef4444'; // red
            }
        } catch (err) {
            statusDiv.innerText = 'Upload failed';
            statusDiv.style.color = '#ef4444';
        } finally {
            btn.disabled = false;
            btn.innerText = 'Upload Marks';
        }
    });
});

function initNavigation() {
    const navItems = document.querySelectorAll('.sidebar-nav li');
    navItems.forEach(item => {
        item.addEventListener('click', (e) => {
            e.preventDefault();
            navItems.forEach(n => n.classList.remove('active'));
            item.classList.add('active');
            
            const view = item.getAttribute('data-view');
            document.querySelectorAll('.view-content').forEach(el => el.style.display = 'none');
            document.getElementById(view + 'View').style.display = 'block';
            
            if(view === 'students') loadStudents();
        });
    });

    const filterBtns = document.querySelectorAll('.filter-btn');
    filterBtns.forEach(btn => {
        btn.addEventListener('click', (e) => {
            filterBtns.forEach(b => {
                b.classList.remove('btn-primary');
                b.classList.add('btn-secondary');
                b.classList.remove('active');
            });
            e.target.classList.remove('btn-secondary');
            e.target.classList.add('btn-primary', 'active');
            
            const testPrefix = e.target.getAttribute('data-filter');
            
            if (testPrefix === 'All') {
                document.getElementById('subFiltersContainer').style.display = 'none';
                loadStudents('All');
            } else {
                fetch(`/api/test-instances?prefix=${encodeURIComponent(testPrefix)}`)
                    .then(res => res.json())
                    .then(data => {
                        const container = document.getElementById('subFiltersContainer');
                        container.innerHTML = '<span style="font-weight: 500; font-size: 1rem; margin-right: 8px; color: #a5b4fc;">Select Instance:</span>';
                        
                        if (!data.instances || data.instances.length === 0) {
                            container.style.display = 'none';
                            loadStudents(testPrefix + ' [No Tests Found]');
                            return;
                        }

                        container.style.display = 'flex';
                        data.instances.forEach((instance, index) => {
                            const subBtn = document.createElement('button');
                            subBtn.className = 'btn btn-sm sub-filter-btn';
                            subBtn.style.padding = '4px 12px';
                            subBtn.style.fontSize = '0.9rem';
                            subBtn.style.borderRadius = '4px';
                            subBtn.style.border = 'none';
                            subBtn.style.cursor = 'pointer';
                            subBtn.style.transition = 'all 0.2s';
                            
                            subBtn.textContent = instance.replace(testPrefix, '').trim() || '1';
                            if (!isNaN(subBtn.textContent)) subBtn.textContent = `Test ${subBtn.textContent}`;
                            
                            // Select last instance by default
                            if (index === data.instances.length - 1) {
                                subBtn.style.backgroundColor = '#6366f1';
                                subBtn.style.color = 'white';
                                loadStudents(instance);
                            } else {
                                subBtn.style.backgroundColor = 'rgba(255,255,255,0.1)';
                                subBtn.style.color = 'white';
                            }

                            subBtn.onclick = (event) => {
                                container.querySelectorAll('.sub-filter-btn').forEach(b => {
                                    b.style.backgroundColor = 'rgba(255,255,255,0.1)';
                                });
                                event.target.style.backgroundColor = '#6366f1';
                                loadStudents(instance);
                            };
                            container.appendChild(subBtn);
                        });

                        // Add Delete button
                        const deleteBtn = document.createElement('button');
                        deleteBtn.className = 'btn btn-sm';
                        deleteBtn.innerHTML = '<i class="fa-solid fa-trash"></i> Delete Test';
                        deleteBtn.style.padding = '4px 12px';
                        deleteBtn.style.fontSize = '0.9rem';
                        deleteBtn.style.borderRadius = '4px';
                        deleteBtn.style.border = 'none';
                        deleteBtn.style.cursor = 'pointer';
                        deleteBtn.style.backgroundColor = 'rgba(239, 68, 68, 0.2)';
                        deleteBtn.style.color = '#ef4444';
                        deleteBtn.style.marginLeft = 'auto'; // push to the right
                        
                        deleteBtn.onclick = () => {
                            // Find currently selected test
                            const selectedTestName = document.getElementById('latestTestNameLabel').innerText;
                            if (confirm(`Are you sure you want to completely delete "${selectedTestName}"? This cannot be undone.`)) {
                                fetch(`/api/test-instances?test_name=${encodeURIComponent(selectedTestName)}`, { method: 'DELETE' })
                                    .then(res => res.json())
                                    .then(resData => {
                                        alert('Test deleted successfully!');
                                        // Reload the current category by clicking the active main filter again
                                        document.querySelector('.filter-btn.active').click();
                                    });
                            }
                        };
                        container.appendChild(deleteBtn);
                    });
            }
        });
    });
}

async function loadDashboardStats() {
    try {
        const res = await fetch('/api/stats');
        const stats = await res.json();
        
        document.getElementById('statTotalStudents').innerText = stats.totalStudents;
        document.getElementById('statAvgScore').innerText = stats.avgScore;
        document.getElementById('statTotalDistricts').innerText = stats.totalDistricts;
        document.getElementById('statTopPerformers').innerText = stats.topPerformers;

        const tbody = document.getElementById('dashboardTableBody');
        tbody.innerHTML = '';
        stats.districtStats.forEach(d => {
            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td>${d.name}</td>
                <td>${d.students}</td>
                <td>${d.avg_score || 0}</td>
                <td>${d.highest || 0}</td>
            `;
            tbody.appendChild(tr);
        });
    } catch (err) {
        console.error("Failed to load stats", err);
    }
}

async function loadDistricts() {
    try {
        const res = await fetch('/api/districts');
        const data = await res.json();
        
        const container = document.getElementById('districtButtonsContainer');
        container.innerHTML = '';
        
        data.districts.forEach(d => {
            const btn = document.createElement('button');
            btn.className = 'btn btn-secondary';
            btn.innerHTML = `<i class="fa-solid fa-upload"></i> ${d.name}`;
            btn.style.padding = '16px 24px';
            btn.style.fontSize = '1.1rem';
            
            btn.addEventListener('click', () => {
                document.getElementById('uploadDistrictName').innerText = d.name;
                document.getElementById('uploadDistrictId').value = d.id;
                document.getElementById('uploadStatus').innerText = '';
                document.getElementById('uploadModal').classList.add('active');
            });
            
            container.appendChild(btn);
        });
    } catch (err) {
        console.error("Failed to load districts", err);
    }
}

let myChart = null;

async function loadStudents(testType = 'All') {
    try {
        document.getElementById('studentsTableContainer').style.display = 'block';
        document.getElementById('chartContainer').style.display = 'block';
        
        let url = '/api/latest-test-scores';
        let isAll = false;
        if (testType === 'All') {
            document.getElementById('studentsTableContainer').style.display = 'none';
            isAll = true;
        } else {
            url = `/api/students?test_type=${encodeURIComponent(testType)}`;
        }
        
        const res = await fetch(url);
        const data = await res.json();
        
        let titleName = data.test_name || testType;
        let studentsData = data.students || [];
        
        document.getElementById('latestTestNameLabel').innerText = titleName;
        
        // Update Chart
        const labels = studentsData.map(s => s.name);
        const scores = studentsData.map(s => s.total_score);
        
        const ctx = document.getElementById('latestTestChart').getContext('2d');
        if (myChart) myChart.destroy();
        
        myChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: labels,
                datasets: [{
                    label: 'Total Score',
                    data: scores,
                    backgroundColor: 'rgba(99, 102, 241, 0.8)',
                    borderColor: 'rgba(99, 102, 241, 1)',
                    borderWidth: 1,
                    borderRadius: 4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                scales: {
                    y: { beginAtZero: true }
                }
            }
        });
        
        if (isAll) return;
        
        const tbody = document.getElementById('studentsTableBody');
        tbody.innerHTML = '';
        
        studentsData.forEach(s => {
            const tr = document.createElement('tr');
            
            // Format score badge
            let scoreBadge = 'average';
            if(s.total_score >= 600) scoreBadge = 'excellent';
            else if(s.total_score >= 450) scoreBadge = 'good';
            
            tr.innerHTML = `
                <td>${s.roll_number}</td>
                <td>${s.name}</td>
                <td>${s.district_name}</td>
                <td><span class="badge-status ${scoreBadge}">${s.total_score || 'N/A'}</span></td>
                <td>
                    <button class="btn btn-secondary" onclick="openEditModal(${s.id})" style="padding: 6px 12px; font-size: 0.8rem; margin-right: 4px;">
                        <i class="fa-solid fa-pen"></i> Edit
                    </button>
                    <button class="btn btn-primary" onclick="viewReport(${s.id})" style="padding: 6px 12px; font-size: 0.8rem;">
                        <i class="fa-solid fa-file-pdf"></i> View Report
                    </button>
                </td>
            `;
            tbody.appendChild(tr);
        });
    } catch (err) {
        console.error("Failed to load students", err);
    }
}

async function openEditModal(studentId) {
    try {
        const res = await fetch(`/api/students/${studentId}`);
        const student = await res.json();
        
        document.getElementById('editStudentId').value = student.id;
        document.getElementById('editDob').value = student.dob || '';
        document.getElementById('editFatherName').value = student.father_name || '';
        document.getElementById('editMotherName').value = student.mother_name || '';
        document.getElementById('editContactNumber').value = student.contact_number || '';
        
        document.getElementById('editStudentModal').classList.add('active');
    } catch (err) {
        console.error("Failed to fetch student details");
    }
}

document.getElementById('editStudentForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const id = document.getElementById('editStudentId').value;
    const data = {
        dob: document.getElementById('editDob').value,
        father_name: document.getElementById('editFatherName').value,
        mother_name: document.getElementById('editMotherName').value,
        contact_number: document.getElementById('editContactNumber').value
    };
    
    try {
        const res = await fetch(`/api/students/${id}`, {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(data)
        });
        if (res.ok) {
            document.getElementById('editStudentModal').classList.remove('active');
            // We don't strictly need to reload the whole list since these fields don't show on the table
            // But doing it for consistency
            loadStudents();
        }
    } catch (err) {
        console.error("Failed to update student");
    }
});

function viewReport(studentId) {
    // Open the PDF report in a new tab
    window.open(`/api/students/${studentId}/report`, '_blank');
}

function initModal() {
    const uploadModal = document.getElementById('uploadModal');
    const closeUploadBtn = document.getElementById('closeModalBtn');
    
    const editModal = document.getElementById('editStudentModal');
    const closeEditBtn = document.getElementById('closeEditModalBtn');

    closeUploadBtn.addEventListener('click', () => uploadModal.classList.remove('active'));
    closeEditBtn.addEventListener('click', () => editModal.classList.remove('active'));

    window.addEventListener('click', (e) => {
        if (e.target === uploadModal) uploadModal.classList.remove('active');
        if (e.target === editModal) editModal.classList.remove('active');
    });
}
document.getElementById('downloadPdfBtn').addEventListener('click', async () => {
    const activeMainFilterBtn = document.querySelector('.filter-btn.active');
    const mainFilterText = activeMainFilterBtn ? activeMainFilterBtn.getAttribute('data-filter') : 'All';
    
    try {
        const btn = document.getElementById('downloadPdfBtn');
        const originalText = btn.innerHTML;
        btn.innerHTML = '<i class=\"fa-solid fa-spinner fa-spin\"></i> Generating...';
        btn.disabled = true;
        
        const res = await fetch(/api/reports/consolidated?prefix= + encodeURIComponent(mainFilterText));
        const data = await res.json();
        
        if (!data.students || data.students.length === 0) {
            alert(\"No data available to generate PDF.\");
            btn.innerHTML = originalText;
            btn.disabled = false;
            return;
        }
        
        const { jsPDF } = window.jspdf;
        const doc = new jsPDF('landscape');
        
        doc.setFontSize(18);
        doc.text(Consolidated Report:  + (mainFilterText === 'All' ? 'All Tests' : mainFilterText), 14, 22);
        
        const head = [['Roll No', 'Name', ...data.tests, 'Overall Avg']];
        const body = data.students.map(s => {
            const row = [s.roll_number, s.name];
            data.tests.forEach(t => {
                row.push(s[t] !== undefined ? s[t] : '-');
            });
            row.push(s.average);
            return row;
        });
        
        doc.autoTable({
            startY: 30,
            head: head,
            body: body,
            theme: 'grid',
            headStyles: { fillColor: [99, 102, 241] },
            styles: { fontSize: 9 }
        });
        
        doc.save(Consolidated_Report_ + mainFilterText.replace(/ /g, '_') + .pdf);
        
        btn.innerHTML = originalText;
        btn.disabled = false;
    } catch (err) {
        console.error(\"PDF Generation Error\", err);
        alert(\"Failed to generate PDF\");
        const btn = document.getElementById('downloadPdfBtn');
        btn.innerHTML = '<i class=\"fa-solid fa-file-pdf\"></i> Download PDF';
        btn.disabled = false;
    }
});
