const { useState, useEffect, useRef } = React;

const FormatK4Upload = () => {
    const [courses, setCourses] = useState([]);
    const [exams, setExams] = useState([]);
    const [loading, setLoading] = useState(true);
    const [selectedCourse, setSelectedCourse] = useState('');
    const [selectedExam, setSelectedExam] = useState('');
    const [previewData, setPreviewData] = useState(null);
    const [error, setError] = useState('');
    const [successMsg, setSuccessMsg] = useState('');

    const fileInputRef = useRef(null);

    useEffect(() => {
        Promise.all([
            fetch('/api/courses').then(res => res.json()),
            fetch('/api/exams').then(res => res.json())
        ]).then(([courseData, examData]) => {
            // Filter only courses that have Summative Assessment of Practical (SA-PR)
            const filteredCourses = courseData.filter(c => parseFloat(c.sa_pr_max) > 0);
            setCourses(filteredCourses);
            setExams(examData);
            
            // Try to auto-select from localStorage if saved by other K4 modules
            try {
                const saved = JSON.parse(localStorage.getItem('k4Filters')) || {};
                if (saved.course && filteredCourses.find(c => String(c.id) === String(saved.course))) {
                    setSelectedCourse(saved.course);
                } else if (filteredCourses.length > 0) {
                    setSelectedCourse(filteredCourses[0].id);
                }
                
                if (saved.exam && examData.find(e => String(e.id) === String(saved.exam))) {
                    setSelectedExam(saved.exam);
                } else if (examData.length > 0) {
                    setSelectedExam(examData[0].id);
                }
            } catch(e) {
                if (filteredCourses.length > 0) setSelectedCourse(filteredCourses[0].id);
                if (examData.length > 0) setSelectedExam(examData[0].id);
            }
            
            setLoading(false);
        }).catch(err => {
            console.error(err);
            setError('Failed to load initial data.');
            setLoading(false);
        });
    }, []);

    const fetchEligibleStudents = async (courseId) => {
        const res = await fetch(`/api/courses/${courseId}/eligible-students?t=${Date.now()}`);
        return res.json();
    };

    const handleDownloadTemplate = async () => {
        if (!selectedCourse || !selectedExam) {
            return setError('Please select both Term and Course first.');
        }
        setLoading(true);
        setError('');
        try {
            const students = await fetchEligibleStudents(selectedCourse);

            if (!students.length) {
                setLoading(false);
                return setError('No eligible students found for this course.');
            }

            const course = courses.find(c => String(c.id) === String(selectedCourse));
            const saMax = parseFloat(course.sa_pr_max) || 50;

            // Header Row
            const headerRow = ['Sr. No.', 'Enrollment No.', 'Student Name', `SA Marks (Max ${saMax})`, 'Student ID (DO NOT EDIT)'];

            const mainData = [headerRow];
            students.sort((a,b) => String(a.enrollment_no||'').localeCompare(String(b.enrollment_no||'')));
            students.forEach((s, i) => {
                mainData.push([i + 1, s.enrollment_no || '', s.full_name || '', '', s.id]);
            });

            const wsMarks = XLSX.utils.aoa_to_sheet(mainData);
            const cols = [{ wch: 8 }, { wch: 20 }, { wch: 35 }, { wch: 25 }, { wch: 30 }];
            wsMarks['!cols'] = cols;

            // Configuration Sheet (Hidden)
            const configData = [
                ['KEY', 'VALUE'],
                ['EXAM_ID', selectedExam],
                ['COURSE_ID', selectedCourse],
                ['COURSE_CODE', course ? course.code : ''],
                ['SA_MAX', saMax]
            ];
            const wsConfig = XLSX.utils.aoa_to_sheet(configData);

            const wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, wsMarks, 'SA-PR Marks');
            XLSX.utils.book_append_sheet(wb, wsConfig, 'CONFIG');

            // Hide config sheet
            if (!wb.Workbook) wb.Workbook = {};
            if (!wb.Workbook.Sheets) wb.Workbook.Sheets = [];
            wb.Workbook.Sheets[1] = { Hidden: 1 };

            XLSX.writeFile(wb, `K4_Template_${course ? course.code.replace(/[^a-z0-9]/gi, '_') : 'COURSE'}.xlsx`);
            
            setLoading(false);
            setSuccessMsg('K4 Excel Template generated successfully!');
            setTimeout(() => setSuccessMsg(''), 5000);
        } catch (err) {
            console.error(err);
            setLoading(false);
            setError('Failed to generate template.');
        }
    };

    const handleFileUpload = (e) => {
        const file = e.target.files[0];
        if (!file) return;
        setLoading(true);
        setError('');
        setPreviewData(null);

        const reader = new FileReader();
        reader.onload = (evt) => {
            try {
                const bstr = evt.target.result;
                const wb = XLSX.read(bstr, { type: 'binary' });
                
                const wsConfig = wb.Sheets['CONFIG'];
                if (!wsConfig) {
                    setLoading(false);
                    return setError('Invalid template. "CONFIG" sheet missing.');
                }
                const configRows = XLSX.utils.sheet_to_json(wsConfig, { header: 1 });
                const config = {};
                configRows.forEach(row => { if(row[0]) config[row[0]] = row[1]; });

                if (!config.EXAM_ID || !config.COURSE_ID || config.SA_MAX === undefined) {
                    setLoading(false);
                    return setError('Malformed metadata. Please re-download the template.');
                }

                const wsMarks = wb.Sheets['SA-PR Marks'] || wb.Sheets[wb.SheetNames[0]];
                const rows = XLSX.utils.sheet_to_json(wsMarks, { header: 1 });

                if (rows.length < 2) {
                    setLoading(false);
                    return setError('No student data found.');
                }

                const headerRow = rows[0];
                const saColIndex = headerRow.findIndex(h => String(h).includes('SA Marks'));
                const enrollColIndex = 1;
                const nameColIndex = 2;
                const idColIndex = headerRow.findIndex(h => String(h).includes('Student ID'));

                if (saColIndex === -1 || idColIndex === -1) {
                    setLoading(false);
                    return setError('Excel columns corrupted. Please use the official template.');
                }

                const parsed = [];
                for (let i = 1; i < rows.length; i++) {
                    const row = rows[i];
                    if (!row || !row[idColIndex]) continue;

                    const studentId = String(row[idColIndex]).trim();
                    const enrollNo = String(row[enrollColIndex] || '').trim();
                    const name = String(row[nameColIndex] || '').trim();
                    const markVal = row[saColIndex];
                    
                    if (markVal !== undefined && markVal !== null && markVal !== '') {
                        const m = parseFloat(markVal);
                        if (!isNaN(m)) {
                           parsed.push({ 
                               studentId, 
                               enrollNo, 
                               name, 
                               mark: m, 
                               isValid: m >= 0 && m <= parseFloat(config.SA_MAX),
                               isAbsent: m === 401
                           });
                        }
                    }
                }

                if (parsed.length === 0) {
                    setLoading(false);
                    return setError('No marks found in the uploaded file.');
                }

                setPreviewData({
                    examId: config.EXAM_ID,
                    courseId: config.COURSE_ID,
                    saMax: config.SA_MAX,
                    marks: parsed
                });
                setLoading(false);
            } catch (err) {
                console.error(err);
                setLoading(false);
                setError('Failed to parse Excel file.');
            }
        };
        reader.readAsBinaryString(file);
    };

    const commitUpload = async () => {
        if (!previewData) return;
        setLoading(true);
        setError('');

        try {
            const payload = previewData.marks.map(s => ({
                student_id: s.studentId,
                max_marks: previewData.saMax,
                marks_obtained: s.mark
            }));

            const res = await fetch('/api/k4-assessments', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ 
                    exam_id: previewData.examId, 
                    course_id: previewData.courseId, 
                    marksData: payload
                })
            });

            if (res.ok) {
                setPreviewData(null);
                setSuccessMsg(`✅ Successfully uploaded K4 SA-PR marks for ${previewData.marks.length} students!`);
                setTimeout(() => setSuccessMsg(''), 8000);
            } else {
                setError('Failed to save marks to database.');
            }
        } catch (err) {
            console.error(err);
            setError('Error communicating with server.');
        }
        setLoading(false);
    };

    if (loading && courses.length === 0) return <div className="p-8 text-center text-lg">Loading Component...</div>;

    return (
        <div className="max-w-6xl mx-auto p-4 md:p-8 animate-fade-in-up">
            <div className="flex justify-between items-center mb-10">
                <div className="flex items-center gap-4">
                    <div className="w-14 h-14 bg-gradient-to-tr from-blue-500 to-indigo-600 rounded-2xl flex items-center justify-center text-2xl font-black text-white shadow-lg pulse-glow">K4</div>
                    <div>
                        <h1 className="text-2xl font-bold text-gray-900 tracking-tight">K4 Bulk SA-PR Upload</h1>
                        <p className="text-blue-600 text-sm font-medium">Summative Practical Assessment Portal</p>
                    </div>
                </div>
            </div>

            {error && <div className="bg-red-50 border border-red-200 text-red-700 p-4 rounded-xl mb-6 text-sm flex items-center gap-2"><span>⚠️</span> {error}</div>}
            {successMsg && <div className="bg-emerald-50 border border-emerald-200 text-emerald-700 p-4 rounded-xl mb-6 text-sm flex items-center gap-2"><span>✅</span> {successMsg}</div>}

            <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                <div className="lg:col-span-1 space-y-6">
                    <div className="bg-white rounded-2xl border border-gray-200 shadow-sm p-6">
                        <h2 className="text-xs font-bold text-blue-600 uppercase tracking-widest mb-6 border-b border-gray-100 pb-2">1. Selection Filter</h2>
                        <div className="space-y-4">
                            <div>
                                <label className="text-[10px] font-bold text-gray-400 uppercase block mb-1.5 tracking-wider">Academic Term</label>
                                <select value={selectedExam} onChange={e => setSelectedExam(e.target.value)} className="w-full bg-gray-50 border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-800 outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition">
                                    {exams.map(e => <option key={e.id} value={e.id}>{e.season} {e.year}</option>)}
                                </select>
                            </div>
                            <div>
                                <label className="text-[10px] font-bold text-gray-400 uppercase block mb-1.5 tracking-wider">Target Course</label>
                                <select value={selectedCourse} onChange={e => setSelectedCourse(e.target.value)} className="w-full bg-gray-50 border border-gray-300 rounded-lg px-3 py-2 text-sm text-gray-800 outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition">
                                    {courses.map(c => <option key={c.id} value={c.id}>{c.code} - {c.name}</option>)}
                                </select>
                            </div>
                            <button onClick={handleDownloadTemplate} className="w-full mt-4 py-3 bg-blue-600 hover:bg-blue-700 text-white font-bold rounded-xl shadow-md transition flex items-center justify-center gap-2 text-sm">
                                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
                                Generate Excel Template
                            </button>
                        </div>
                    </div>
                </div>

                <div className="lg:col-span-2">
                    <div 
                        className="bg-white rounded-2xl border-2 border-dashed border-gray-300 h-full flex flex-col items-center justify-center p-10 cursor-pointer hover:border-blue-500/50 hover:bg-blue-50/20 transition-all" 
                        onClick={() => fileInputRef.current.click()}
                    >
                        <div className="w-20 h-20 bg-blue-50 rounded-full flex items-center justify-center text-4xl mb-6 shadow-inner">📊</div>
                        <h2 className="text-xl font-bold text-gray-800 mb-2">Upload Completed Template</h2>
                        <p className="text-gray-500 text-center max-w-sm text-sm">Drop the filled K4 SA-PR Excel file here, or click to browse.</p>
                        <input ref={fileInputRef} type="file" accept=".xlsx,.xls" className="hidden" onChange={handleFileUpload} />
                    </div>
                </div>
            </div>

            {previewData && (
                <div className="mt-10 bg-white rounded-2xl border border-gray-200 shadow-xl overflow-hidden animate-fade-in-up">
                    <div className="px-6 py-4 bg-gray-50 border-b border-gray-200 flex justify-between items-center flex-wrap gap-4">
                        <div>
                            <h3 className="text-lg font-bold text-gray-900 flex items-center gap-2">
                                <div className="w-2 h-2 rounded-full bg-blue-500"></div> Preview Parsed Data
                            </h3>
                            <p className="text-xs text-gray-500 font-medium">{previewData.marks.length} students identified with SA entries.</p>
                        </div>
                        <div className="flex gap-3">
                            <button onClick={() => setPreviewData(null)} className="px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 text-sm rounded-lg font-bold transition">Cancel</button>
                            <button onClick={commitUpload} className="px-8 py-2 bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white font-black text-sm rounded-lg shadow-lg transition transform hover:scale-105">
                                ✓ Confirm & Commit to Database
                            </button>
                        </div>
                    </div>
                    <div className="overflow-x-auto max-h-[500px] border-t border-gray-100">
                        <table className="w-full text-left">
                            <thead className="sticky top-0 bg-gray-50 text-[10px] uppercase font-bold text-gray-400 border-b border-gray-200 shadow-sm">
                                <tr>
                                    <th className="px-4 py-4 text-center w-12">#</th>
                                    <th className="px-4 py-4 w-32">Enrollment</th>
                                    <th className="px-4 py-4">Student Name</th>
                                    <th className="px-4 py-4 text-center border-l border-gray-100 w-48">SA Marks (Max {previewData.saMax})</th>
                                    <th className="px-4 py-4 text-center w-32">Status</th>
                                </tr>
                            </thead>
                            <tbody className="divide-y divide-gray-100 text-sm">
                                {previewData.marks.map((m, i) => (
                                    <tr key={m.studentId} className="hover:bg-blue-50/20 transition-colors">
                                        <td className="px-4 py-3 text-center text-gray-400 text-xs font-bold">{i+1}</td>
                                        <td className="px-4 py-3 text-gray-600 font-mono text-xs">{m.enrollNo}</td>
                                        <td className="px-4 py-3 text-gray-900 font-bold truncate max-w-[200px]">{m.name}</td>
                                        <td className={`px-4 py-3 text-center border-l border-gray-50 font-black text-lg ${m.isAbsent ? 'text-orange-600' : (!m.isValid ? 'text-red-600' : 'text-blue-700')}`}>
                                            {m.mark}
                                        </td>
                                        <td className="px-4 py-3 text-center">
                                            {!m.isValid ? (
                                                <span className="bg-red-100 text-red-700 text-[10px] font-black px-2 py-0.5 rounded uppercase">Out of Range</span>
                                            ) : m.isAbsent ? (
                                                <span className="bg-orange-100 text-orange-700 text-[10px] font-black px-2 py-0.5 rounded uppercase">Absent</span>
                                            ) : (
                                                <span className="bg-emerald-100 text-emerald-700 text-[10px] font-black px-2 py-0.5 rounded uppercase">OK</span>
                                            )}
                                        </td>
                                    </tr>
                                ))}
                            </tbody>
                        </table>
                    </div>
                </div>
            )}
            
            {loading && (
                <div className="fixed inset-0 bg-white/40 backdrop-blur-sm flex items-center justify-center z-50">
                    <div className="bg-white p-6 rounded-2xl shadow-2xl border border-gray-100 flex flex-col items-center gap-4">
                        <div className="w-10 h-10 border-4 border-blue-500 border-t-transparent rounded-full animate-spin"></div>
                        <p className="text-blue-900 font-bold tracking-widest text-xs uppercase">Processing...</p>
                    </div>
                </div>
            )}
        </div>
    );
};

window.FormatK4Upload = FormatK4Upload;
