const { useState, useEffect, useMemo } = React;

const CourseAllocationMaster = ({ currentUser }) => {
  const [exams, setExams] = useState([]);
  const [courses, setCourses] = useState([]);
  const [allFaculties, setAllFaculties] = useState([]);
  const [batches, setBatches] = useState([]);
  // allocations map: key = `${course_id}_${allocType}` for Theory
  //                  key = `${course_id}_${allocType}_${batch_id}` for Practical/Tutorial
  const [allocations, setAllocations] = useState({});
  const [selectedExamId, setSelectedExamId] = useState('');
  const [selectedSemester, setSelectedSemester] = useState('All');
  const [searchQuery, setSearchQuery] = useState('');
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [savedMsg, setSavedMsg] = useState('');

  useEffect(() => {
    fetchExams();
    fetchFaculties();
    fetchBatches();
  }, []);

  useEffect(() => {
    if (selectedExamId) {
      fetchCourses();
      fetchExistingAllocations();
    }
  }, [selectedExamId]);

  const selectedExam = useMemo(() =>
    exams.find(ex => ex.id === parseInt(selectedExamId)),
    [exams, selectedExamId]
  );

  const fetchExams = async () => {
    try {
      const res = await fetch('/api/exams');
      if (res.ok) setExams(await res.json());
    } catch (err) { console.error(err); }
  };

  const fetchFaculties = async () => {
    try {
      const res = await fetch('/api/auth/faculties-for-allocation');
      if (res.ok) setAllFaculties(await res.json());
    } catch (err) { console.error(err); }
  };

  const fetchBatches = async () => {
    try {
      const res = await fetch('/api/batches');
      if (res.ok) setBatches(await res.json());
    } catch (err) { console.error(err); }
  };

  const fetchCourses = async () => {
    setLoading(true);
    try {
      const roles = (currentUser && currentUser.role) ? currentUser.role.split(',') : [];
      const isDeptAdmin = roles.some(r => ['HOD', 'Assistant'].includes(r));
      const isGlobalAdmin = roles.some(r => ['Administrator', 'Principal'].includes(r));
      let deptFilter = '';
      if (isDeptAdmin && !isGlobalAdmin) {
        const targetDeptId = currentUser.hod_dept_id || currentUser.dept_id;
        if (targetDeptId) deptFilter = `&dept_id=${targetDeptId}`;
      }
      const res = await fetch(`/api/courses?${deptFilter}`);
      if (res.ok) setCourses(await res.json());
    } catch (err) { console.error(err); }
    finally { setLoading(false); }
  };

  const fetchExistingAllocations = async () => {
    try {
      const roles = (currentUser && currentUser.role) ? currentUser.role.split(',') : [];
      const isDeptAdmin = roles.some(r => ['HOD', 'Assistant'].includes(r));
      const isGlobalAdmin = roles.some(r => ['Administrator', 'Principal'].includes(r));
      let deptFilter = '';
      if (isDeptAdmin && !isGlobalAdmin) {
        const targetDeptId = currentUser.hod_dept_id || currentUser.dept_id;
        if (targetDeptId) deptFilter = `&dept_id=${targetDeptId}`;
      }
      const res = await fetch(`/api/course-allocations?exam_id=${selectedExamId}${deptFilter}`);
      if (res.ok) {
        const data = await res.json();
        const map = {};
        data.forEach(a => {
          // Theory: key without batch; Practical/Tutorial: key with batch_id
          if (a.allocation_type === 'Theory') {
            map[`${a.course_id}_Theory`] = a.faculty_id;
          } else {
            // One entry per batch
            const batchId = a.batch_id || 'none';
            map[`${a.course_id}_${a.allocation_type}_${batchId}`] = a.faculty_id;
          }
        });
        setAllocations(map);
      }
    } catch (err) { console.error(err); }
  };

  const filteredCourses = useMemo(() => {
    if (!selectedExam) return [];
    const isWinter = selectedExam.season.toLowerCase() === 'winter';
    let filtered = courses.filter(c => {
      const sem = parseInt(c.semester);
      return isWinter ? (sem % 2 !== 0) : (sem % 2 === 0);
    });
    if (selectedSemester !== 'All') {
      filtered = filtered.filter(c => parseInt(c.semester) === parseInt(selectedSemester));
    }
    if (searchQuery) {
      const q = searchQuery.toLowerCase();
      filtered = filtered.filter(c =>
        c.name.toLowerCase().includes(q) || c.code.toLowerCase().includes(q)
      );
    }
    return filtered;
  }, [courses, selectedExam, selectedSemester, searchQuery]);

  const handleAllocationChange = (courseId, allocType, facultyId, batchId = null) => {
    const key = allocType === 'Theory'
      ? `${courseId}_Theory`
      : `${courseId}_${allocType}_${batchId || 'none'}`;
    setAllocations(prev => ({ ...prev, [key]: facultyId }));
  };

  const handleSave = async () => {
    if (!selectedExamId) { alert('Please select an exam first'); return; }
    setSaving(true);
    setSavedMsg('');

    const payload = [];
    Object.entries(allocations).forEach(([key, faculty_id]) => {
      if (!faculty_id) return;
      const parts = key.split('_');
      const course_id = parts[0];
      const allocation_type = parts[1];
      const batch_id = parts[2] && parts[2] !== 'none' ? parseInt(parts[2]) : null;

      payload.push({
        course_id: parseInt(course_id),
        faculty_id: parseInt(faculty_id),
        allocation_type,
        batch_id,
        exam_id: parseInt(selectedExamId),
        academic_year: selectedExam.year.toString()
      });
    });

    try {
      const res = await fetch('/api/course-allocations', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ allocations: payload })
      });
      if (res.ok) {
        setSavedMsg('Allocations saved successfully!');
        setTimeout(() => setSavedMsg(''), 3000);
      } else {
        const d = await res.json();
        alert(d.error || 'Failed to save');
      }
    } catch (err) { alert('Network error'); }
    finally { setSaving(false); }
  };

  // ── Sub-components ─────────────────────────────────────────────────────────

  const FacultySelect = ({ courseId, allocType, batchId = null, colorClass }) => {
    const key = allocType === 'Theory'
      ? `${courseId}_Theory`
      : `${courseId}_${allocType}_${batchId || 'none'}`;
    const currentVal = allocations[key] || '';
    return (
      <select
        value={currentVal}
        onChange={(e) => handleAllocationChange(courseId, allocType, e.target.value, batchId)}
        className={`w-full text-[11px] px-2 py-2 border-2 rounded-xl focus:outline-none focus:ring-2 bg-white transition-all appearance-none cursor-pointer hover:bg-gray-50 ${colorClass}`}
      >
        <option value="">— Unassigned —</option>
        {allFaculties.map(f => (
          <option key={f.id} value={f.id}>
            {f.salutation} {f.first_name} {f.last_name} ({f.Department?.dept_code || '??'})
          </option>
        ))}
      </select>
    );
  };

  // ── Batch rows for Practical / Tutorial ────────────────────────────────────
  const BatchAllocRows = ({ courseId, allocType }) => {
    const colorClass = allocType === 'Tutorial'
      ? 'border-amber-200 focus:ring-amber-400 focus:border-amber-400'
      : 'border-emerald-200 focus:ring-emerald-400 focus:border-emerald-400';
    const dotColor = allocType === 'Tutorial' ? 'bg-amber-500' : 'bg-emerald-500';
    const textColor = allocType === 'Tutorial' ? 'text-amber-600' : 'text-emerald-600';

    if (batches.length === 0) {
      return (
        <div className="space-y-2">
          <label className={`flex items-center gap-1.5 text-[9px] font-black uppercase ${textColor} tracking-wider`}>
            <span className={`w-1.5 h-1.5 rounded-full ${dotColor}`} /> {allocType} Loading
          </label>
          <FacultySelect courseId={courseId} allocType={allocType} colorClass={colorClass} />
        </div>
      );
    }

    return (
      <div className="space-y-3">
        <label className={`flex items-center gap-1.5 text-[9px] font-black uppercase ${textColor} tracking-wider`}>
          <span className={`w-1.5 h-1.5 rounded-full ${dotColor}`} /> {allocType} — Per Batch
        </label>
        <div className="space-y-2">
          {batches.map(batch => (
            <div key={batch.id} className="flex items-center gap-2">
              <span className={`text-[10px] font-black shrink-0 w-8 text-center py-1.5 rounded-lg border ${
                allocType === 'Tutorial' ? 'bg-amber-50 text-amber-700 border-amber-200' : 'bg-emerald-50 text-emerald-700 border-emerald-200'
              }`}>
                {batch.batch_name}
              </span>
              <div className="flex-1">
                <FacultySelect
                  courseId={courseId}
                  allocType={allocType}
                  batchId={batch.id}
                  colorClass={colorClass}
                />
              </div>
            </div>
          ))}
        </div>
      </div>
    );
  };

  // ── Render ─────────────────────────────────────────────────────────────────
  return (
    <div className="animate-fade-in-up space-y-6 max-w-[1600px] mx-auto pb-20">
      {/* Header */}
      <div className="bg-white/80 backdrop-blur-md p-6 rounded-[2rem] shadow-xl shadow-blue-900/5 border border-white flex flex-wrap gap-6 items-center justify-between sticky top-0 z-30">
        <div className="flex items-center gap-4">
          <div className="w-14 h-14 bg-gradient-to-br from-blue-600 to-indigo-700 rounded-2xl flex items-center justify-center shadow-lg shadow-blue-200">
            <span className="text-2xl">📋</span>
          </div>
          <div>
            <h2 className="text-2xl font-black text-gray-900 tracking-tight">Subject Allocation</h2>
            <div className="flex items-center gap-2 mt-1">
              <span className="text-xs font-bold px-2 py-0.5 rounded-full bg-blue-100 text-blue-700 uppercase tracking-wider">
                {currentUser?.dept_name || 'System Wide'}
              </span>
              <span className="text-gray-300">|</span>
              <p className="text-xs text-gray-500 font-medium">Theory (class-wide) · Practical & Tutorial (per batch)</p>
            </div>
          </div>
        </div>

        <div className="flex items-center gap-3 flex-wrap">
          <div className="relative">
            <select
              value={selectedExamId}
              onChange={(e) => { setSelectedExamId(e.target.value); setSelectedSemester('All'); }}
              className="pl-4 pr-10 py-3 border-2 border-gray-100 rounded-2xl focus:ring-4 focus:ring-blue-100 focus:border-blue-500 outline-none bg-gray-50/50 font-bold text-sm transition-all appearance-none cursor-pointer min-w-[220px]"
            >
              <option value="">Select Exam Term...</option>
              {exams.map(ex => <option key={ex.id} value={ex.id}>{ex.year} — {ex.season}</option>)}
            </select>
            <div className="absolute right-3 top-1/2 -translate-y-1/2 pointer-events-none text-gray-400">▼</div>
          </div>

          {selectedExamId && (
            <button
              onClick={handleSave}
              disabled={saving}
              className="bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-700 hover:to-indigo-700 text-white px-8 py-3 rounded-2xl font-bold transition-all shadow-lg shadow-blue-200 active:scale-95 disabled:opacity-50 flex items-center gap-2"
            >
              {saving ? <div className="w-4 h-4 border-2 border-white/30 border-t-white rounded-full animate-spin" /> : '💾'}
              {saving ? 'Saving...' : 'Save Changes'}
            </button>
          )}
        </div>
      </div>

      {savedMsg && (
        <div className="bg-emerald-50 border border-emerald-200 text-emerald-700 px-6 py-4 rounded-2xl font-bold flex items-center gap-3 animate-bounce shadow-sm">
          <span className="bg-emerald-500 text-white w-6 h-6 flex items-center justify-center rounded-full text-xs">✓</span>
          {savedMsg}
        </div>
      )}

      {/* Filters */}
      {selectedExamId && (
        <div className="grid grid-cols-1 md:grid-cols-12 gap-4 items-center bg-white p-4 rounded-[1.5rem] shadow-sm border border-gray-100">
          <div className="md:col-span-4 relative group">
            <input
              type="text"
              placeholder="Search by code or name..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              className="w-full pl-10 pr-4 py-2.5 bg-gray-50 border-2 border-gray-100 rounded-xl focus:border-blue-500 focus:bg-white outline-none text-sm transition-all"
            />
            <span className="absolute left-3 top-1/2 -translate-y-1/2 text-gray-400">🔍</span>
          </div>

          <div className="md:col-span-4 flex items-center gap-2 overflow-x-auto no-scrollbar">
            <button onClick={() => setSelectedSemester('All')}
              className={`px-4 py-2 rounded-xl text-xs font-bold transition-all whitespace-nowrap ${selectedSemester === 'All' ? 'bg-blue-600 text-white shadow-md' : 'bg-gray-100 text-gray-500 hover:bg-gray-200'}`}>
              All Sem
            </button>
            {(selectedExam?.season.toLowerCase() === 'winter' ? [1,3,5,7] : [2,4,6,8]).map(s => (
              <button key={s} onClick={() => setSelectedSemester(s.toString())}
                className={`px-4 py-2 rounded-xl text-xs font-bold transition-all ${selectedSemester === s.toString() ? 'bg-blue-600 text-white shadow-md' : 'bg-gray-100 text-gray-500 hover:bg-gray-200'}`}>
                Sem {s}
              </button>
            ))}
          </div>

          <div className="md:col-span-4 flex justify-end gap-4 text-[10px] font-bold uppercase tracking-widest text-gray-400 flex-wrap">
            <div className="flex items-center gap-1.5"><div className="w-2.5 h-2.5 rounded-full bg-blue-500" /> Theory (Class)</div>
            <div className="flex items-center gap-1.5"><div className="w-2.5 h-2.5 rounded-full bg-amber-500" /> Tutorial (Batch)</div>
            <div className="flex items-center gap-1.5"><div className="w-2.5 h-2.5 rounded-full bg-emerald-500" /> Practical (Batch)</div>
          </div>
        </div>
      )}

      {/* Table */}
      {selectedExamId ? (
        <div className="bg-white rounded-[2rem] shadow-xl shadow-gray-200/50 border border-gray-100 overflow-hidden min-h-[400px]">
          {loading ? (
            <div className="flex flex-col items-center justify-center h-80 gap-4">
              <div className="w-12 h-12 border-4 border-blue-100 border-t-blue-600 rounded-full animate-spin" />
              <p className="text-gray-400 font-bold animate-pulse uppercase tracking-widest text-xs">Loading Course Catalog...</p>
            </div>
          ) : filteredCourses.length === 0 ? (
            <div className="flex flex-col items-center justify-center h-80 gap-4 text-center p-10">
              <div className="text-6xl grayscale opacity-20">🗃️</div>
              <div>
                <h3 className="text-lg font-bold text-gray-800">No Subjects Found</h3>
                <p className="text-sm text-gray-400 max-w-xs mx-auto">No subjects match the selected filters for this {selectedExam?.season} term.</p>
                <button onClick={() => { setSearchQuery(''); setSelectedSemester('All'); }} className="mt-4 text-blue-600 font-bold text-xs uppercase hover:underline">Clear Filters</button>
              </div>
            </div>
          ) : (
            <div className="overflow-x-auto overflow-y-visible">
              <table className="w-full text-left border-collapse">
                <thead>
                  <tr className="bg-gray-50/50 border-b border-gray-100 text-gray-400 text-[10px] font-black uppercase tracking-tighter">
                    <th className="p-6 w-80">Subject Details</th>
                    <th className="p-6 w-24 text-center">Sem</th>
                    <th className="p-6">
                      <div className="flex items-center gap-6">
                        <span className="text-blue-500">Theory</span>
                        <span className="text-amber-500">Tutorial (per batch)</span>
                        <span className="text-emerald-500">Practical (per batch)</span>
                      </div>
                    </th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-gray-50">
                  {filteredCourses.map(course => {
                    const hasTheory = course.fa_th_max > 0 || course.sa_th_max > 0;
                    const hasPractical = course.fa_pr_max > 0 || course.sa_pr_max > 0;
                    const hasTutorial = course.tl > 0;

                    return (
                      <tr key={course.id} className="group hover:bg-blue-50/30 transition-colors">
                        {/* Subject info */}
                        <td className="p-6 align-top">
                          <div className="flex items-start gap-4">
                            <div className="w-12 h-12 rounded-2xl bg-gray-100 flex items-center justify-center font-black text-gray-400 group-hover:bg-blue-600 group-hover:text-white transition-all shadow-inner shrink-0">
                              {course.abbreviation || course.code.slice(-2)}
                            </div>
                            <div>
                              <div className="font-black text-gray-900 group-hover:text-blue-700 transition-colors">{course.name}</div>
                              <div className="flex items-center gap-2 mt-1">
                                <span className="text-[10px] font-bold text-gray-400 font-mono bg-gray-50 px-1.5 rounded">{course.code}</span>
                                <span className="text-[10px] font-bold text-blue-400">{course.scheme}</span>
                              </div>
                            </div>
                          </div>
                        </td>

                        {/* Semester */}
                        <td className="p-6 text-center align-top">
                          <span className="inline-block w-8 h-8 rounded-full bg-blue-50 text-blue-700 font-black text-sm leading-8 shadow-sm">
                            {course.semester}
                          </span>
                        </td>

                        {/* Assignments */}
                        <td className="p-6 align-top">
                          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">

                            {/* Theory — class-wide, single dropdown */}
                            {hasTheory ? (
                              <div className="space-y-2">
                                <label className="flex items-center gap-1.5 text-[9px] font-black uppercase text-blue-600 tracking-wider">
                                  <span className="w-1.5 h-1.5 rounded-full bg-blue-500" /> Theory (Class-wide)
                                </label>
                                <FacultySelect
                                  courseId={course.id}
                                  allocType="Theory"
                                  colorClass="border-blue-200 focus:ring-blue-400 focus:border-blue-400"
                                />
                              </div>
                            ) : <div className="hidden lg:block" />}

                            {/* Tutorial — per batch */}
                            {hasTutorial ? (
                              <BatchAllocRows courseId={course.id} allocType="Tutorial" />
                            ) : <div className="hidden lg:block" />}

                            {/* Practical — per batch */}
                            {hasPractical ? (
                              <BatchAllocRows courseId={course.id} allocType="Practical" />
                            ) : <div className="hidden lg:block" />}

                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>
      ) : (
        <div className="bg-white/40 backdrop-blur-sm rounded-[3rem] border-4 border-dashed border-gray-200 p-24 text-center">
          <div className="w-32 h-32 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-6 text-6xl shadow-inner">⏳</div>
          <h3 className="text-2xl font-black text-gray-800 tracking-tight">Ready for Allocation</h3>
          <p className="text-gray-400 mt-2 max-w-sm mx-auto font-medium">Please select an academic term from the dropdown above to start mapping subjects to faculty.</p>
        </div>
      )}
    </div>
  );
};

window.CourseAllocationMaster = CourseAllocationMaster;
