const { useState, useEffect } = React;

const ManageExamStudents = ({ examId, courseId, assessmentType, instituteId, onClose, onSaved }) => {
  const [students, setStudents] = useState([]);
  const [course, setCourse] = useState(null);
  const [loading, setLoading] = useState(true);
  const [search, setSearch] = useState('');

  useEffect(() => {
    if (!examId || !courseId || !assessmentType) return;
    
    Promise.all([
      fetch(`/api/courses/${courseId}`).then(res => res.json()),
      fetch(`/api/courses/${courseId}/all-department-students`).then(res => res.json()),
      fetch(`/api/courses/${courseId}/eligible-students?exam_id=${examId}&assessment_type=${assessmentType}`).then(res => res.json())
    ]).then(([courseData, allData, eligibleData]) => {
      setCourse(courseData);
      const eligibleIds = new Set(Array.isArray(eligibleData) ? eligibleData.map(s => s.id) : []);
      
      const mapped = (Array.isArray(allData) ? allData : []).map(s => {
        // If they are currently in the eligible list (which already accounts for roster and natural eligibility), they are checked
        return { ...s, _assigned: eligibleIds.has(s.id) };
      });
      // Sort so checked students (currently eligible) appear at the top, then by enrollment no
      mapped.sort((a, b) => {
        if (a._assigned && !b._assigned) return -1;
        if (!a._assigned && b._assigned) return 1;
        return String(a.enrollment_no || '').localeCompare(String(b.enrollment_no || ''));
      });
      setStudents(mapped);
      setLoading(false);
    });
  }, [examId, courseId, assessmentType]);

  const toggleStudent = (id) => {
    setStudents(prev => prev.map(s => s.id === id ? { ...s, _assigned: !s._assigned } : s));
  };

  const handleSave = async () => {
    // Only send explicit overrides to the database to save space
    const assignments = students.map(s => {
      // Natural eligibility: If current semester matches course semester, active profile, and Academic status Pass/ATKT (for sem > 1)
      const isActive = !s.status || s.status === 'Active';
      const isSemMatch = String(s.current_semester || s.semester) === String(course?.semester);
      const isAcademicEligible = Number(course?.semester) <= 1 || (s.last_exam_status && ['pass', 'atkt'].includes(String(s.last_exam_status).toLowerCase()));
      const isNaturallyEligible = isSemMatch && isActive && isAcademicEligible;
      // We need an explicit record if they deviate from natural eligibility
      const isDeviation = (s._assigned !== isNaturallyEligible);
      
      if (isDeviation) {
        return { student_id: s.id, is_assigned: s._assigned };
      }
      return null;
    }).filter(Boolean);

    try {
      const res = await fetch(`/api/courses/${courseId}/roster`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ exam_id: examId, assessment_type: assessmentType, assignments })
      });
      if (res.ok) {
        if(onSaved) onSaved();
      } else {
        alert("Failed to save student assignments");
      }
    } catch(e) {
      alert("Error saving");
    }
  };

  const filtered = students.filter(s => 
    (s.full_name || '').toLowerCase().includes(search.toLowerCase()) || 
    (s.enrollment_no || '').toLowerCase().includes(search.toLowerCase())
  );

  return (
    <div className="fixed inset-0 bg-black/60 backdrop-blur-sm flex items-center justify-center z-[100] p-4">
      <div className="bg-white rounded-2xl shadow-2xl w-full max-w-2xl overflow-hidden flex flex-col max-h-[90vh]">
        <div className="p-4 border-b border-gray-100 flex items-center justify-between bg-gray-50">
          <h2 className="text-lg font-bold text-gray-800">Assign / De-assign Students</h2>
          <button onClick={onClose} className="text-gray-400 hover:text-red-500 font-bold">&times; Close</button>
        </div>
        
        <div className="p-4 border-b border-gray-100">
          <input 
            type="text" 
            placeholder="Search by name or enrollment..." 
            value={search} 
            onChange={e => setSearch(e.target.value)}
            className="w-full px-4 py-2 border border-gray-200 rounded-lg text-sm outline-none focus:border-blue-400"
          />
        </div>

        <div className="flex-1 overflow-y-auto p-4 bg-gray-50/50">
          {loading ? (
            <div className="text-center py-10 text-gray-400">Loading students...</div>
          ) : (
            <table className="w-full text-left text-sm bg-white rounded-lg shadow-sm border border-gray-100">
              <thead className="bg-gray-100/50 text-gray-500 sticky top-0">
                <tr>
                  <th className="px-4 py-3 border-b border-gray-100 w-16 text-center">Assign</th>
                  <th className="px-4 py-3 border-b border-gray-100">Enrollment No</th>
                  <th className="px-4 py-3 border-b border-gray-100">Name</th>
                  <th className="px-4 py-3 border-b border-gray-100 text-center">Sem</th>
                  <th className="px-4 py-3 border-b border-gray-100">Batch</th>
                  <th className="px-4 py-3 border-b border-gray-100 text-center">Status</th>
                </tr>
              </thead>
              <tbody>
                {filtered.map(s => (
                  <tr key={s.id} className="border-b border-gray-50 hover:bg-gray-50/50 cursor-pointer" onClick={() => toggleStudent(s.id)}>
                    <td className="px-4 py-2 text-center">
                      <input 
                        type="checkbox" 
                        checked={s._assigned} 
                        onChange={() => {}} // handled by row click
                        className="w-4 h-4 cursor-pointer" 
                      />
                    </td>
                    <td className="px-4 py-2 text-gray-600">{s.enrollment_no}</td>
                    <td className="px-4 py-2 font-medium text-gray-800">{s.full_name}</td>
                    <td className="px-4 py-2 text-center">
                      <span className="bg-gray-100 text-gray-600 text-[10px] font-bold px-2 py-0.5 rounded">Sem {s.current_semester || s.semester}</span>
                    </td>
                    <td className="px-4 py-2 text-gray-500">{s.Batch?.batch_name || '-'}</td>
                    <td className="px-4 py-2 text-center">
                      <span className={`text-[10px] font-bold px-2 py-0.5 rounded ${
                        (s.status || 'Active') === 'Active' ? 'bg-emerald-50 text-emerald-700' : 'bg-gray-100 text-gray-600'
                      }`}>
                        {s.status || 'Active'}
                      </span>
                      {s.last_exam_status && (
                        <span className="ml-1 text-[9px] font-bold text-gray-400">({s.last_exam_status})</span>
                      )}
                    </td>
                  </tr>
                ))}
                {filtered.length === 0 && (
                  <tr><td colSpan={4} className="text-center py-8 text-gray-400">No students found</td></tr>
                )}
              </tbody>
            </table>
          )}
        </div>

        <div className="p-4 border-t border-gray-100 bg-white flex justify-end gap-3">
          <button onClick={onClose} className="px-6 py-2 rounded-lg text-sm font-bold text-gray-600 bg-gray-100 hover:bg-gray-200">Cancel</button>
          <button onClick={handleSave} className="px-6 py-2 rounded-lg text-sm font-bold text-white bg-blue-600 hover:bg-blue-700">Save Assignments</button>
        </div>
      </div>
    </div>
  );
};

window.ManageExamStudents = ManageExamStudents;

