import { useState, useEffect, useRef } from 'react';
import api from '../../store/auth';
import { Avatar } from '../../components/Avatar';
import { useEducationTerms } from '../../utils/educationTerms';
import { Modal, ModalBody } from '../../components/ui/Modal';
import {
  Plus, Edit2, Trash2, Building2, Users,
  BookOpen, Search, X, ChevronRight,
  Download, Filter, Sparkles, Target,
  CheckCircle2, AlertCircle, Info, MoreHorizontal,
  Mail, Phone, ShieldCheck, GraduationCap
} from 'lucide-react';

/** Trigger a CSV download of the current list state. */
function exportToCsv(filename: string, rows: Record<string, unknown>[]) {
  if (rows.length === 0) return;
  const headers = Object.keys(rows[0]);
  const escape = (v: unknown) => {
    const s = v == null ? '' : String(v);
    return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
  };
  const csv = [headers.join(','), ...rows.map(r => headers.map(h => escape(r[h])).join(','))].join('\n');
  const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
}

interface Department {
  id: number;
  name: string;
  code?: string;
  description?: string;
  head_teacher_id?: number;
  head_name?: string;
  teacher_count: number;
  student_count: number;
  subject_count: number;
}

interface SubjectToAdd {
  tempId: string;
  name: string;
  code: string;
  class_id: string;
  teacher_id: string;
  syllabus: File | null;
  syllabus_name: string;
}

interface SearchableSelectProps {
  label: string;
  placeholder: string;
  options: { value: string | number; label: string }[];
  value: string;
  onChange: (value: string) => void;
}

function SearchableSelect({ label, placeholder, options, value, onChange }: SearchableSelectProps) {
  const [isOpen, setIsOpen] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const wrapperRef = useRef<HTMLDivElement>(null);
  
  const selectedOption = options.find(o => o.value.toString() === value);
  const filteredOptions = options.filter(o => 
    o.label.toLowerCase().includes(searchTerm.toLowerCase())
  );

  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (wrapperRef.current && !wrapperRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [wrapperRef]);

  return (
    <div ref={wrapperRef} className="space-y-1.5 relative flex-1">
      <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">{label}</label>
      <div 
        className="w-full bg-muted/50 border border-border rounded-2xl px-5 py-4 text-sm font-semibold focus-within:ring-4 focus-within:ring-blue-500/5 focus-within:bg-card focus-within:border-primary transition-all text-text cursor-pointer flex justify-between items-center relative dark:bg-background/50 h-[54px]"
        onClick={() => setIsOpen(!isOpen)}
      >
        <span className={selectedOption ? "text-text truncate pr-4" : "text-text-muted/40 truncate pr-4"}>
          {selectedOption ? selectedOption.label : placeholder}
        </span>
        <ChevronRight size={16} className={`text-text-muted/50 transition-transform shrink-0 ${isOpen ? 'rotate-90' : ''}`} />
      </div>

      {isOpen && (
        <div className="absolute z-[250] left-0 right-0 mt-2 bg-card border border-border rounded-2xl shadow-xl overflow-hidden max-h-60 flex flex-col animate-in fade-in slide-in-from-top-1 duration-150">
          <div className="p-3 border-b border-border bg-muted/20 flex items-center gap-2">
            <Search size={14} className="text-text-muted/50" />
            <input
              type="text"
              className="bg-transparent border-0 w-full text-xs font-semibold focus:outline-none focus:ring-0 text-text placeholder:text-text-muted/40"
              placeholder="Search options..."
              value={searchTerm}
              onChange={e => setSearchTerm(e.target.value)}
              onClick={e => e.stopPropagation()}
              autoFocus
            />
            {searchTerm && (
              <button 
                type="button" 
                onClick={(e) => { e.stopPropagation(); setSearchTerm(''); }}
                className="text-text-muted hover:text-text"
              >
                <X size={12} />
              </button>
            )}
          </div>
          <div className="overflow-y-auto flex-1 custom-scrollbar max-h-44 divide-y divide-border/20">
            {filteredOptions.length === 0 ? (
              <div className="p-4 text-center text-xs font-semibold text-text-muted uppercase tracking-wider">
                No matches found
              </div>
            ) : (
              filteredOptions.map(opt => (
                <div
                  key={opt.value}
                  className={`px-5 py-3 text-xs font-semibold hover:bg-primary/10 hover:text-primary transition-colors cursor-pointer flex items-center justify-between ${opt.value.toString() === value ? 'bg-primary/5 text-primary' : 'text-text'}`}
                  onClick={(e) => {
                    e.stopPropagation();
                    onChange(opt.value.toString());
                    setIsOpen(false);
                    setSearchTerm('');
                  }}
                >
                  <span>{opt.label}</span>
                  {opt.value.toString() === value && <CheckCircle2 size={12} className="text-primary shrink-0" />}
                </div>
              ))
            )}
          </div>
        </div>
      )}
    </div>
  );
}

export default function Departments() {
  const terms = useEducationTerms();
  const [departments, setDepartments] = useState<Department[]>([]);
  const [showModal, setShowModal] = useState(false);
  const [showSubjectModal, setShowSubjectModal] = useState(false);
  const [showViewModal, setShowViewModal] = useState(false);
  const [selectedDept, setSelectedViewDept] = useState<Department | null>(null);
  const [loading, setLoading] = useState(true);
  const [editingId, setEditingId] = useState<number | null>(null);
  const [editingSubjectId, setEditingSubjectId] = useState<number | null>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [teachers, setTeachers] = useState<any[]>([]);
  const [classes, setClasses] = useState<any[]>([]);
  const [deleteSyllabus, setDeleteSyllabus] = useState(false);

  const [showAddSubjectForm, setShowAddSubjectForm] = useState(false);
  const [newSubForm, setNewSubForm] = useState({
    name: '',
    class_id: '',
    teacher_id: '',
    syllabus: null as File | null,
    syllabus_name: ''
  });
  const [subjectsToAdd, setSubjectsToAdd] = useState<SubjectToAdd[]>([]);
  const [deletedSubjectIds, setDeletedSubjectIds] = useState<number[]>([]);
  const [editingListTempId, setEditingListTempId] = useState<string | null>(null);

  useEffect(() => {
    loadDepartments();
    loadTeachers();
    loadClasses();
  }, []);

  const loadTeachers = async () => {
    try {
      const res = await api.get('/users', { params: { role: 'teacher', limit: 100 } });
      const data = res.data.users || res.data;
      setTeachers(Array.isArray(data) ? data : []);
    } catch (err) {
      console.error('Failed to load faculty records');
    }
  };

  const loadClasses = async () => {
    try {
      const res = await api.get('/classes');
      setClasses(res.data);
    } catch (err) {
      console.error('Failed to load classes');
    }
  };

  const loadDepartments = async () => {
    setLoading(true);
    try {
      const res = await api.get('/departments');
      setDepartments(res.data.map((d: any) => ({
        ...d,
        head_name: d.head_teacher_name || '',
        teacher_count: d.teacher_count || 0,
        student_count: d.student_count || 0,
        subject_count: d.subject_count || 0,
      })));
    } catch (err) {
      console.error('Failed to load department records');
    } finally {
      setLoading(false);
    }
  };

  const handleViewDept = async (dept: Department) => {
    setSelectedViewDept(dept);
    setShowViewModal(true);
    try {
      const res = await api.get(`/departments/${dept.id}`);
      setSelectedViewDept({
        ...res.data,
        head_name: res.data.head_teacher_name || '',
        teacher_count: res.data.teacher_count || 0,
        student_count: res.data.student_count || 0,
        subject_count: res.data.subject_count || 0,
      });
    } catch (err) {
      console.error('Failed to load department details');
    }
  };

  const refreshViewDept = async (deptId: number) => {
    try {
      const res = await api.get(`/departments/${deptId}`);
      setSelectedViewDept({
        ...res.data,
        head_name: res.data.head_teacher_name || '',
        teacher_count: res.data.teacher_count || 0,
        student_count: res.data.student_count || 0,
        subject_count: res.data.subject_count || 0,
      });
    } catch (err) {
      console.error('Failed to refresh department details');
    }
  };

  const [form, setForm] = useState({ 
    name: '', 
    description: '', 
    head_teacher_id: '',
    code: '',
    teacher_ids: [] as number[]
  });
  const [subjectForm, setSubjectForm] = useState({
    name: '',
    code: '',
    class_id: '',
    department_id: '',
    teacher_id: '',
    syllabus: null as File | null,
    syllabus_name: ''
  });

  useEffect(() => {
    if (!subjectForm.name || !subjectForm.class_id) {
      setSubjectForm(prev => ({ ...prev, code: '' }));
      return;
    }
    
    // Generate code
    const namePart = subjectForm.name
      .trim()
      .replace(/[^a-zA-Z\s]/g, '')
      .split(/\s+/)
      .map(w => w[0])
      .join('')
      .toUpperCase();
    
    const subjCode = namePart.length >= 3 ? namePart : subjectForm.name.trim().substring(0, 4).toUpperCase();
    
    const selectedClass = classes.find(c => c.id.toString() === subjectForm.class_id);
    let classCode = 'GEN';
    if (selectedClass) {
      const cName = selectedClass.name.toUpperCase();
      if (cName.includes('FORM')) {
        classCode = 'F' + cName.replace(/[^0-9]/g, '');
      } else if (cName.includes('GRADE')) {
        classCode = 'G' + cName.replace(/[^0-9]/g, '');
      } else if (cName.includes('LOWER')) {
        classCode = 'L6';
      } else if (cName.includes('UPPER')) {
        classCode = 'U6';
      } else {
        classCode = cName.replace(/[^A-Z0-9]/g, '').substring(0, 3);
      }
    }
    
    const generatedCode = `${subjCode}-${classCode}`;
    setSubjectForm(prev => ({ ...prev, code: generatedCode }));
  }, [subjectForm.name, subjectForm.class_id, classes]);

  // Generate department code from name
  useEffect(() => {
    if (!form.name) {
      setForm(prev => ({ ...prev, code: '' }));
      return;
    }
    
    const cleaned = form.name.trim().replace(/[^a-zA-Z\s]/g, '');
    const words = cleaned.split(/\s+/);
    let generatedCode = '';
    if (words.length >= 3) {
      generatedCode = words.map(w => w[0]).join('').toUpperCase();
    } else if (words.length === 2) {
      generatedCode = (words[0].substring(0, 2) + words[1].substring(0, 2)).toUpperCase();
    } else {
      const word = words[0];
      generatedCode = word.length >= 4 ? word.substring(0, 4).toUpperCase() : word.toUpperCase();
    }
    
    setForm(prev => ({ ...prev, code: generatedCode }));
  }, [form.name]);

  const generateSubjectCode = (subName: string, classId: string) => {
    if (!subName || !classId) return '';
    const namePart = subName
      .trim()
      .replace(/[^a-zA-Z\s]/g, '')
      .split(/\s+/)
      .map(w => w[0])
      .join('')
      .toUpperCase();
    
    const subjCode = namePart.length >= 3 ? namePart : subName.trim().substring(0, 4).toUpperCase();
    
    const selectedClass = classes.find(c => c.id.toString() === classId);
    let classCode = 'GEN';
    if (selectedClass) {
      const cName = selectedClass.name.toUpperCase();
      if (cName.includes('FORM')) {
        classCode = 'F' + cName.replace(/[^0-9]/g, '');
      } else if (cName.includes('GRADE')) {
        classCode = 'G' + cName.replace(/[^0-9]/g, '');
      } else if (cName.includes('LOWER')) {
        classCode = 'L6';
      } else if (cName.includes('UPPER')) {
        classCode = 'U6';
      } else {
        classCode = cName.replace(/[^A-Z0-9]/g, '').substring(0, 3);
      }
    }
    return `${subjCode}-${classCode}`;
  };

  const handleAddSubjectToList = () => {
    if (!newSubForm.name || !newSubForm.class_id) {
      alert('Subject Name and Class/Section are required');
      return;
    }
    const code = generateSubjectCode(newSubForm.name, newSubForm.class_id);
    
    if (editingListTempId) {
      setSubjectsToAdd(prev => prev.map(s => {
        if (s.tempId === editingListTempId) {
          return {
            ...s,
            name: newSubForm.name,
            code,
            class_id: newSubForm.class_id,
            teacher_id: newSubForm.teacher_id,
            syllabus: newSubForm.syllabus,
            syllabus_name: newSubForm.syllabus_name
          };
        }
        return s;
      }));
      setEditingListTempId(null);
    } else {
      const sub: SubjectToAdd = {
        tempId: Date.now().toString(),
        name: newSubForm.name,
        code,
        class_id: newSubForm.class_id,
        teacher_id: newSubForm.teacher_id,
        syllabus: newSubForm.syllabus,
        syllabus_name: newSubForm.syllabus_name
      };
      setSubjectsToAdd(prev => [...prev, sub]);
    }
    
    setNewSubForm({ name: '', class_id: '', teacher_id: '', syllabus: null, syllabus_name: '' });
    setShowAddSubjectForm(false);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    try {
      let deptId = editingId;
      if (editingId) {
        await api.put(`/departments/${editingId}`, form);
      } else {
        const res = await api.post('/departments', form);
        deptId = res.data.id;
      }

      // Process deleted subjects
      for (const subId of deletedSubjectIds) {
        await api.delete(`/subjects/${subId}`);
      }

      // Save or update subjects in the modal
      for (const sub of subjectsToAdd) {
        const formData = new FormData();
        formData.append('name', sub.name);
        formData.append('code', sub.code);
        formData.append('class_id', sub.class_id);
        formData.append('department_id', deptId!.toString());
        formData.append('teacher_id', sub.teacher_id);
        if (sub.syllabus) {
          formData.append('syllabus', sub.syllabus);
        }
        
        const config = {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        };

        if (sub.id) {
          await api.put(`/subjects/${sub.id}`, formData, config);
        } else {
          await api.post('/subjects', formData, config);
        }
      }

      setShowModal(false);
      setForm({ name: '', description: '', head_teacher_id: '', code: '', teacher_ids: [] });
      setSubjectsToAdd([]);
      setDeletedSubjectIds([]);
      setEditingListTempId(null);
      setEditingId(null);
      loadDepartments();
      if (selectedDept) {
        refreshViewDept(selectedDept.id);
      }
    } catch (err) {
      alert('Error saving department');
    }
  };

  const handleSubjectSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!subjectForm.class_id) {
      alert('Associate with Section is required');
      return;
    }
    if (!subjectForm.department_id) {
      alert('Academic Department is required');
      return;
    }
    try {
      const formData = new FormData();
      formData.append('name', subjectForm.name);
      formData.append('code', subjectForm.code);
      formData.append('class_id', subjectForm.class_id);
      formData.append('department_id', subjectForm.department_id);
      formData.append('teacher_id', subjectForm.teacher_id);
      
      if (subjectForm.syllabus) {
        formData.append('syllabus', subjectForm.syllabus);
      }
      if (deleteSyllabus) {
        formData.append('delete_syllabus', 'true');
      }

      const config = {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      };

      if (editingSubjectId) {
        await api.put(`/subjects/${editingSubjectId}`, formData, config);
      } else {
        await api.post('/subjects', formData, config);
      }

      setShowSubjectModal(false);
      setSubjectForm({
        name: '',
        code: '',
        class_id: '',
        department_id: '',
        teacher_id: '',
        syllabus: null,
        syllabus_name: ''
      });
      setDeleteSyllabus(false);
      setEditingSubjectId(null);

      loadDepartments();
      if (selectedDept) {
        refreshViewDept(selectedDept.id);
      }
    } catch (err) {
      alert('Failed to save subject record');
    }
  };

  const openAddSubject = () => {
    setSubjectForm({
      name: '',
      code: '',
      class_id: '',
      department_id: '',
      teacher_id: '',
      syllabus: null,
      syllabus_name: ''
    });
    setDeleteSyllabus(false);
    setEditingSubjectId(null);
    setShowSubjectModal(true);
  };

  const openAddSubjectForDept = (deptId: number) => {
    setSubjectForm({
      name: '',
      code: '',
      class_id: '',
      department_id: deptId.toString(),
      teacher_id: '',
      syllabus: null,
      syllabus_name: ''
    });
    setDeleteSyllabus(false);
    setEditingSubjectId(null);
    setShowSubjectModal(true);
  };

  const openEditSubject = (sub: any) => {
    setSubjectForm({
      name: sub.name,
      code: sub.code || '',
      class_id: sub.class_id ? sub.class_id.toString() : '',
      department_id: sub.department_id ? sub.department_id.toString() : '',
      teacher_id: sub.teacher_id ? sub.teacher_id.toString() : '',
      syllabus: null,
      syllabus_name: sub.syllabus_name || ''
    });
    setDeleteSyllabus(false);
    setEditingSubjectId(sub.id);
    setShowSubjectModal(true);
  };

  const deleteSubject = async (id: number) => {
    if (!confirm('Archive this subject record?')) return;
    try {
      await api.delete(`/subjects/${id}`);
      loadDepartments();
      if (selectedDept) {
        refreshViewDept(selectedDept.id);
      }
    } catch (err) {
      alert('Failed to archive subject');
    }
  };

  const handleEdit = async (dept: Department) => {
    setForm({ 
      name: dept.name, 
      description: dept.description || '', 
      head_teacher_id: dept.head_teacher_id?.toString() || '',
      code: (dept as any).code || '',
      teacher_ids: [] as number[]
    });
    setSubjectsToAdd([]);
    setDeletedSubjectIds([]);
    setEditingListTempId(null);
    setEditingId(dept.id);
    setShowModal(true);

    try {
      const res = await api.get(`/departments/${dept.id}`);
      const fullDept = res.data;
      setForm({ 
        name: fullDept.name, 
        description: fullDept.description || '', 
        head_teacher_id: fullDept.head_teacher_id?.toString() || '',
        code: fullDept.code || '',
        teacher_ids: fullDept.teachers ? fullDept.teachers.map((t: any) => t.id) : []
      });

      const existingSubjects = fullDept.subjects ? fullDept.subjects.map((sub: any) => ({
        tempId: `existing_${sub.id}`,
        id: sub.id,
        name: sub.name,
        code: sub.code || '',
        class_id: sub.class_id ? sub.class_id.toString() : '',
        teacher_id: sub.teacher_id ? sub.teacher_id.toString() : '',
        syllabus: null,
        syllabus_name: sub.syllabus_name || ''
      })) : [];
      setSubjectsToAdd(existingSubjects);
    } catch (err) {
      console.error('Failed to load full department details for edit');
    }
  };

  const deleteDepartment = async (id: number) => {
    if (!confirm('Archive this department record? This will affect curriculum organization.')) return;
    try {
      await api.delete(`/departments/${id}`);
      loadDepartments();
      if (selectedDept && selectedDept.id === id) {
        setShowViewModal(false);
      }
    } catch (err) {
      alert('Failed to archive record');
    }
  };

  const filteredDepartments = departments.filter(d => 
    d.name.toLowerCase().includes(searchQuery.toLowerCase())
  );

  const stats = [
    { label: 'Academic Units', value: departments.length, icon: Building2, color: 'blue' },
    { label: 'Faculty Leaders', value: departments.filter(d => d.head_name).length || departments.length, icon: ShieldCheck, color: 'emerald' },
    { label: 'Student Population', value: departments.reduce((acc, d) => acc + d.student_count, 0), icon: Users, color: 'orange' },
    { label: 'Curriculum Assets', value: departments.reduce((acc, d) => acc + d.subject_count, 0), icon: BookOpen, color: 'purple' },
  ];

  return (
    <div className="space-y-10 animate-in fade-in duration-700 pb-10">
      {/* Premium Header */}
      <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6">
        <div>
          <h2 className="text-3xl font-black text-text tracking-tight text-capitalize text-slate-900 dark:text-white">Academic Units</h2>
          <nav className="flex text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted gap-2 items-center mt-1">
            <span>Administration</span>
            <ChevronRight size={12} className="text-text-muted/30" />
            <span className="text-primary">Department Summary</span>
          </nav>
        </div>
        <div className="flex gap-3">
          <button
            onClick={() => exportToCsv(
              `academic_units_${new Date().toISOString().split('T')[0]}.csv`,
              filteredDepartments.map(d => ({
                id: d.id,
                name: d.name,
                description: d.description ?? '',
                head_name: d.head_name ?? '',
                teacher_count: d.teacher_count,
                student_count: d.student_count,
                subject_count: d.subject_count
              }))
            )}
            className="flex items-center gap-2 px-5 py-2.5 bg-card border border-border text-text rounded-xl font-bold text-sm hover:bg-muted/50 transition-all shadow-sm active:scale-95"
          >
            <Download size={18} />
            Unit Archive
          </button>
          <button 
            className="flex items-center gap-2 px-6 py-2.5 bg-primary text-white rounded-xl font-bold text-sm hover:bg-primary/90 transition-all shadow-lg shadow-blue-900/10 active:scale-95"
            onClick={() => { setEditingId(null); setForm({ name: '', description: '', head_teacher_id: '', code: '', teacher_ids: [] }); setShowModal(true); }}
          >
            <Plus size={18} />
            Establish Department
          </button>
        </div>
      </div>

      {/* Stats Bento Grid */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {stats.map((stat) => (
          <div key={stat.label} className="bg-card border border-border p-5 rounded-2xl flex items-center gap-4 hover:shadow-md transition-all group cursor-default">
            <div className={`w-12 h-12 rounded-2xl flex items-center justify-center 
              ${stat.color === 'blue' ? 'bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 border-blue-100 dark:border-blue-800' : 
                stat.color === 'emerald' ? 'bg-emerald-50 dark:bg-emerald-900/20 text-emerald-600 dark:text-emerald-400 border-emerald-100 dark:border-emerald-800' : 
                stat.color === 'orange' ? 'bg-orange-50 dark:bg-orange-900/20 text-orange-600 dark:text-orange-400 border-orange-100 dark:border-orange-800' : 
                'bg-purple-50 dark:bg-purple-900/20 text-purple-600 dark:text-purple-400 border-purple-100 dark:border-purple-800'} 
              group-hover:scale-110 transition-transform border`}>
              <stat.icon size={22} />
            </div>
            <div>
              <p className="text-[0.65rem] font-black uppercase tracking-wider text-text-muted">{stat.label}</p>
              <div className="flex items-baseline gap-2">
                <p className="text-2xl font-black text-text">{stat.value}</p>
                <span className="text-[0.6rem] font-bold text-text-muted">Active</span>
              </div>
            </div>
          </div>
        ))}
      </div>

      {/* Directory Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
        {loading ? (
            <div className="col-span-full py-20 text-center">
                <div className="w-10 h-10 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
                <p className="text-text-muted font-bold uppercase tracking-widest text-[0.65rem]">Loading...</p>
            </div>
        ) : filteredDepartments.map((dept) => (
            <div 
              key={dept.id} 
              className="bg-card rounded-[2.5rem] border border-border p-8 hover:shadow-xl hover:shadow-blue-900/5 transition-all group cursor-pointer relative overflow-hidden flex flex-col"
              onClick={() => handleViewDept(dept)}
            >
                <div className="absolute top-0 right-0 w-32 h-32 bg-muted rounded-bl-[4rem] -mr-16 -mt-16 group-hover:bg-blue-50/10 dark:group-hover:bg-blue-900/20 transition-colors"></div>
                
                <div className="relative z-10 flex justify-between items-start mb-6 shrink-0">
                    <div className="w-14 h-14 rounded-2xl bg-primary flex items-center justify-center text-white shadow-lg shadow-blue-900/10 group-hover:scale-110 transition-transform">
                        <Building2 size={28} />
                    </div>
                    <div className="flex gap-2">
                        <button 
                            onClick={(e) => { e.stopPropagation(); handleEdit(dept); }}
                            className="p-2 bg-card rounded-xl border border-border text-text-muted hover:text-primary hover:border-primary transition-all shadow-sm opacity-0 group-hover:opacity-100"
                        >
                            <Edit2 size={16} />
                        </button>
                        <button 
                            onClick={(e) => { e.stopPropagation(); deleteDepartment(dept.id); }}
                            className="p-2 bg-card rounded-xl border border-border text-text-muted hover:text-rose-500 hover:border-rose-100 transition-all shadow-sm opacity-0 group-hover:opacity-100"
                        >
                            <Trash2 size={16} />
                        </button>
                    </div>
                </div>

                <div className="relative z-10 mb-8 flex-grow">
                    <h3 className="text-2xl font-black text-text tracking-tighter group-hover:text-primary transition-colors truncate">{dept.name}</h3>
                    <div className="flex gap-2 items-center mt-1">
                        <span className="text-[0.6rem] font-black uppercase tracking-wider px-2 py-0.5 rounded bg-primary/10 text-primary border border-primary/20">
                            {dept.code || 'NO-CODE'}
                        </span>
                        <p className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted truncate">ID: UNIT-2024-{dept.id}</p>
                    </div>
                </div>

                <div className="relative z-10 grid grid-cols-3 gap-3">
                    <div className="bg-muted p-4 rounded-2xl border border-border group-hover:bg-card transition-colors text-center">
                        <Users size={12} className="text-primary mx-auto mb-1" />
                        <p className="text-sm font-black text-text">{dept.teacher_count}</p>
                        <p className="text-[0.5rem] font-black uppercase text-text-muted">Staff</p>
                    </div>
                    <div className="bg-muted p-4 rounded-2xl border border-border group-hover:bg-card transition-colors text-center">
                        <GraduationCap size={12} className="text-emerald-500 mx-auto mb-1" />
                        <p className="text-sm font-black text-text">{dept.student_count}</p>
                        <p className="text-[0.5rem] font-black uppercase text-text-muted">Learner</p>
                    </div>
                    <div className="bg-muted p-4 rounded-2xl border border-border group-hover:bg-card transition-colors text-center">
                        <BookOpen size={12} className="text-orange-500 mx-auto mb-1" />
                        <p className="text-sm font-black text-text">{dept.subject_count}</p>
                        <p className="text-[0.5rem] font-black uppercase text-text-muted">Syllabus</p>
                    </div>
                </div>

                <div className="mt-8 pt-6 border-t border-border flex items-center justify-between shrink-0">
                    <span className="text-[0.6rem] font-black uppercase tracking-widest text-emerald-500">Active</span>
                    <div className="flex items-center gap-1 text-primary text-[0.65rem] font-black uppercase tracking-widest group-hover:translate-x-1 transition-transform">
                        Detailed Audit <ChevronRight size={14} />
                    </div>
                </div>
            </div>
        ))}

        {!loading && filteredDepartments.length === 0 && (
          <div className="col-span-full py-24 text-center bg-card border-2 border-dashed border-border rounded-[3rem]">
            <Building2 size={64} className="mx-auto text-text-muted/20 mb-6" />
            <h3 className="text-2xl font-black text-text mb-2 uppercase tracking-tighter">Registry Clear</h3>
                <p className="text-text-muted font-medium max-w-xs mx-auto">No subjects match your current filter.</p>
          </div>
        )}
      </div>

      {/* Creation Modal */}
      {showModal && (
        <Modal
          open={true}
          onClose={() => setShowModal(false)}
          title={editingId ? 'Update Department' : 'Establish Department'}
          icon={Sparkles}
          maxWidth="max-w-xl"
          zIndex={150}
        >
          <ModalBody className="p-0">
            <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden">
              <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12">
                <Sparkles size={180} />
              </div>
              <div className="relative z-10">
                <h2 className="text-2xl font-black text-text tracking-tight uppercase">{editingId ? 'Update Department' : 'Establish Department'}</h2>
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">Configure academic structure</p>
              </div>
            </div>

            <form onSubmit={handleSubmit} className="p-10 space-y-6 max-h-[70vh] overflow-y-auto custom-scrollbar">
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Department Name</label>
                <input
                  className="w-full bg-muted/50 border border-border rounded-2xl px-5 py-4 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all placeholder:text-text-muted/30 dark:bg-background/50"
                  value={form.name}
                  onChange={(e) => setForm({ ...form, name: e.target.value })}
                  placeholder="e.g., Pure Sciences Division"
                  required
                />
              </div>

              <SearchableSelect
                label="Head of Department"
                placeholder="Select faculty leader..."
                options={teachers.map(t => ({ value: t.id, label: `${t.first_name} ${t.last_name}` }))}
                value={form.head_teacher_id}
                onChange={(val) => {
                  setForm(prev => {
                    const currentTeachers = [...prev.teacher_ids];
                    if (val && !currentTeachers.includes(parseInt(val))) {
                      currentTeachers.push(parseInt(val));
                    }
                    return { ...prev, head_teacher_id: val, teacher_ids: currentTeachers };
                  });
                }}
              />

              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Scope & Objectives</label>
                <textarea
                  className="w-full bg-muted/50 border border-border rounded-2xl px-5 py-4 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all placeholder:text-text-muted/30"
                  rows={3}
                  value={form.description}
                  onChange={(e) => setForm({ ...form, description: e.target.value })}
                  placeholder="Outline the primary academic focus of this unit..."
                />
              </div>

              <div className="space-y-1.5">
                <SearchableSelect
                  label="Assign Teachers"
                  placeholder="Select teacher to add..."
                  options={teachers.map(t => ({ value: t.id, label: `${t.first_name} ${t.last_name}` }))}
                  value=""
                  onChange={(val) => {
                    if (val) {
                      const id = parseInt(val);
                      if (!form.teacher_ids.includes(id)) {
                        setForm(prev => ({ ...prev, teacher_ids: [...prev.teacher_ids, id] }));
                      }
                    }
                  }}
                />
                  
                {form.teacher_ids.length > 0 && (
                  <div className="mt-3 flex flex-wrap gap-2 p-3 bg-muted/20 border border-border rounded-2xl max-h-32 overflow-y-auto custom-scrollbar">
                    {form.teacher_ids.map(tId => {
                      const teacher = teachers.find(t => t.id === tId);
                      if (!teacher) return null;
                      return (
                        <div key={tId} className="flex items-center gap-2 px-3 py-1.5 bg-card border border-border rounded-xl text-xs font-semibold text-text shadow-sm">
                          <span>{teacher.first_name} {teacher.last_name}</span>
                          <button
                            type="button"
                            onClick={() => {
                              setForm(prev => ({
                                ...prev,
                                teacher_ids: prev.teacher_ids.filter(id => id !== tId),
                                head_teacher_id: prev.head_teacher_id === tId.toString() ? '' : prev.head_teacher_id
                              }));
                            }}
                            className="text-text-muted hover:text-rose-500 transition-colors"
                          >
                            <X size={12} />
                          </button>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>

              <div className="space-y-4 pt-4 border-t border-border">
                <div className="flex justify-between items-center">
                  <label className="text-[0.65rem] font-black uppercase tracking-[2px] text-text-muted px-1">{terms.subjects} to Add</label>
                  <button
                    type="button"
                    onClick={() => setShowAddSubjectForm(!showAddSubjectForm)}
                    className="flex items-center gap-1.5 px-3 py-1.5 bg-primary/10 text-primary border border-primary/20 rounded-xl font-bold text-[0.6rem] uppercase tracking-wider hover:bg-primary/20 transition-all active:scale-95"
                  >
                    {showAddSubjectForm ? <X size={12} /> : <Plus size={12} />}
                    {showAddSubjectForm ? 'Cancel' : `New ${terms.subject}`}
                  </button>
                </div>

                {showAddSubjectForm && (
                  <div className="p-5 bg-muted/30 border border-border border-dashed rounded-2xl space-y-4">
                    <div className="space-y-1.5">
                      <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">{terms.subject} Name</label>
                      <input
                        className="w-full bg-card border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text"
                        placeholder="e.g., General Mathematics"
                        value={newSubForm.name}
                        onChange={e => setNewSubForm({ ...newSubForm, name: e.target.value })}
                      />
                    </div>
                    
                    <div className="grid grid-cols-2 gap-4">
                      <SearchableSelect
                        label="Class/Section"
                        placeholder="Select section..."
                        options={classes.map(c => ({ value: c.id, label: `${c.name} ${c.section ? `(${c.section})` : ''}` }))}
                        value={newSubForm.class_id}
                        onChange={val => setNewSubForm({ ...newSubForm, class_id: val })}
                      />
                      <SearchableSelect
                        label="Assign Teacher"
                        placeholder="Select teacher..."
                        options={teachers.map(t => ({ value: t.id, label: `${t.first_name} ${t.last_name}` }))}
                        value={newSubForm.teacher_id}
                        onChange={val => setNewSubForm({ ...newSubForm, teacher_id: val })}
                      />
                    </div>

                    <div className="space-y-1.5">
                      <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Upload Syllabus (Optional)</label>
                      <input
                        type="file"
                        accept=".pdf,.doc,.docx,.png,.jpg,.jpeg"
                        className="w-full bg-card border border-border rounded-xl px-4 py-3 text-xs font-semibold focus:outline-none focus:border-primary transition-all text-text file:mr-4 file:py-1 file:px-3 file:rounded-lg file:border-0 file:text-[0.6rem] file:font-semibold file:bg-primary/10 file:text-primary hover:file:bg-primary/20 cursor-pointer"
                        onChange={e => {
                          if (e.target.files && e.target.files[0]) {
                            setNewSubForm({ ...newSubForm, syllabus: e.target.files[0], syllabus_name: e.target.files[0].name });
                          }
                        }}
                      />
                    </div>

                    <button
                      type="button"
                      onClick={handleAddSubjectToList}
                      className="w-full py-3 bg-primary text-white font-black uppercase tracking-widest text-[0.65rem] rounded-xl hover:bg-primary/90 transition-all active:scale-95"
                    >
                      {editingListTempId ? `Update ${terms.subject} in List` : `Add ${terms.subject} to List`}
                    </button>
                  </div>
                )}

                {subjectsToAdd.length > 0 && (
                  <div className="divide-y divide-border border border-border rounded-2xl overflow-hidden bg-card">
                    {subjectsToAdd.map((sub) => {
                      const selectedClass = classes.find(c => c.id.toString() === sub.class_id);
                      const selectedTeacher = teachers.find(t => t.id.toString() === sub.teacher_id);
                      return (
                        <div key={sub.tempId} className="p-4 flex items-center justify-between hover:bg-muted/10 transition-colors">
                          <div>
                            <p className="text-xs font-bold text-text">{sub.name}</p>
                            <p className="text-[0.55rem] font-black text-text-muted uppercase tracking-wider mt-0.5">
                              Code: {sub.code} | Class: {selectedClass ? selectedClass.name : 'N/A'} | Teacher: {selectedTeacher ? `${selectedTeacher.first_name} ${selectedTeacher.last_name}` : 'N/A'}
                            </p>
                            {sub.syllabus_name && (
                              <p className="text-[0.55rem] font-black text-indigo-500 uppercase tracking-widest mt-0.5">
                                Syllabus: {sub.syllabus_name}
                              </p>
                            )}
                          </div>
                          <div className="flex items-center gap-2">
                            <button
                              type="button"
                              onClick={() => {
                                setNewSubForm({
                                  name: sub.name,
                                  class_id: sub.class_id,
                                  teacher_id: sub.teacher_id,
                                  syllabus: sub.syllabus,
                                  syllabus_name: sub.syllabus_name
                                });
                                setEditingListTempId(sub.tempId);
                                setShowAddSubjectForm(true);
                              }}
                              className="p-1.5 bg-muted rounded-lg border border-border text-text-muted hover:text-primary transition-colors"
                            >
                              <Edit2 size={12} />
                            </button>
                            <button
                              type="button"
                              onClick={() => {
                                if (sub.id) {
                                  setDeletedSubjectIds(prev => [...prev, sub.id!]);
                                }
                                setSubjectsToAdd(prev => prev.filter(s => s.tempId !== sub.tempId));
                                if (editingListTempId === sub.tempId) {
                                  setEditingListTempId(null);
                                  setNewSubForm({ name: '', class_id: '', teacher_id: '', syllabus: null, syllabus_name: '' });
                                }
                              }}
                              className="p-1.5 bg-muted rounded-lg border border-border text-text-muted hover:text-rose-500 transition-colors"
                            >
                              <X size={12} />
                            </button>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>

              <button type="submit" className="w-full py-5 bg-primary hover:bg-primary/90 text-white font-black uppercase tracking-widest text-xs rounded-2xl transition-all shadow-xl active:scale-95 flex items-center justify-center gap-3">
                <CheckCircle2 size={18} />
                Finalize Unit Records
              </button>
            </form>
          </ModalBody>
        </Modal>
      )}

      {/* View Details Modal */}
      {showViewModal && selectedDept && (
        <Modal
          open={true}
          onClose={() => setShowViewModal(false)}
          title={selectedDept.name}
          icon={Building2}
          maxWidth="max-w-xl"
          zIndex={150}
        >
          <ModalBody className="p-0">
            <div className="p-10 pb-8 bg-muted/50 border-b border-border flex items-center justify-between shrink-0 relative overflow-hidden">
                <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12">
                    <Building2 size={180} />
                </div>
              <div className="relative z-10 flex items-center gap-6">
                <div className="w-16 h-16 rounded-2xl bg-primary flex items-center justify-center text-white shadow-xl">
                    <Building2 size={32} />
                </div>
                <div>
                    <h2 className="text-2xl font-black text-text tracking-tight uppercase">{selectedDept.name}</h2>
                    <div className="flex gap-2 items-center mt-1">
                        <span className="text-[0.65rem] font-black uppercase tracking-wider px-2 py-0.5 rounded bg-primary/20 text-primary border border-primary/30">
                            {selectedDept.code || 'NO-CODE'}
                        </span>
                        <p className="text-[0.65rem] font-black text-primary uppercase tracking-[3px]">Department Overview</p>
                    </div>
                </div>
              </div>
            </div>

            <div className="p-10 overflow-y-auto flex-1 custom-scrollbar space-y-10">
                <div className="space-y-4">
                    <h4 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted px-1">Unit Mandate</h4>
                    <div className="p-8 bg-blue-50/10 dark:bg-blue-900/20 border border-blue-100/20 dark:border-blue-800/30 rounded-[2rem] relative overflow-hidden">
                        <p className="text-lg font-medium text-text-secondary leading-relaxed">
                            {selectedDept.description || 'This unit focuses on advanced academic synchronization across multiple disciplines.'}
                        </p>
                    </div>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
                    <div className="space-y-4">
                        <h4 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted px-1">Strategic Leadership</h4>
                        <div className="bg-muted/50 border border-border rounded-3xl p-6 flex items-center gap-4 group">
                            <div className="w-14 h-14 rounded-2xl bg-card border border-border flex items-center justify-center text-primary shadow-sm group-hover:scale-105 transition-transform">
                                <ShieldCheck size={24} />
                            </div>
                            <div>
                                <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-widest">Head of Department</p>
                                <p className="text-[0.95rem] font-bold text-text uppercase">{selectedDept.head_name || 'Dr. Elena Vance'}</p>
                            </div>
                        </div>
                    </div>
                    <div className="space-y-4">
                        <h4 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted px-1">Assigned Resources</h4>
                        <div className="grid grid-cols-2 gap-4">
                            <div className="bg-card border border-border rounded-3xl p-6 text-center shadow-sm">
                                <p className="text-2xl font-black text-text">{selectedDept.teacher_count}</p>
                                <p className="text-[0.55rem] font-black text-text-muted uppercase tracking-widest">Staffing</p>
                            </div>
                            <div className="bg-card border border-border rounded-3xl p-6 text-center shadow-sm">
                                <p className="text-2xl font-black text-text">{selectedDept.subject_count}</p>
                                <p className="text-[0.55rem] font-black text-text-muted uppercase tracking-widest">Syllabuses</p>
                            </div>
                        </div>
                    </div>
                </div>

                <div className="space-y-6">
                    <h4 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted px-1">Staffing</h4>
                    <div className="bg-card border border-border rounded-[2rem] overflow-hidden shadow-sm">
                        <div className="p-4 bg-muted/30 border-b border-border text-[0.6rem] font-black uppercase tracking-widest text-primary flex justify-between">
                            <span>Verified Faculty</span>
                            <span>Direct Intel</span>
                        </div>
                        <div className="divide-y divide-border">
                            {selectedDept.teachers && selectedDept.teachers.length > 0 ? (
                              selectedDept.teachers.map((teacher: any) => (
                                <div key={teacher.id} className="p-4 flex items-center justify-between hover:bg-muted/50 transition-colors cursor-default">
                                    <div className="flex items-center gap-3">
                                        <div className="w-10 h-10 rounded-xl bg-muted border border-border overflow-hidden">
                                            <Avatar firstName={teacher.first_name} lastName={teacher.last_name} />
                                        </div>
                                        <div>
                                            <p className="text-sm font-bold text-text">{teacher.first_name} {teacher.last_name}</p>
                                            <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-tight">{teacher.designation || 'Teacher'}</p>
                                        </div>
                                    </div>
                                    <div className="flex gap-2">
                                        {teacher.email && (
                                          <a href={`mailto:${teacher.email}`} className="p-2 text-text-muted hover:text-primary transition-all" title="Email staff"><Mail size={14} /></a>
                                        )}
                                        {teacher.phone && (
                                          <a href={`tel:${teacher.phone}`} className="p-2 text-text-muted hover:text-primary transition-all" title="Call staff"><Phone size={14} /></a>
                                        )}
                                    </div>
                                </div>
                              ))
                            ) : (
                              <div className="p-8 text-center text-text-muted text-xs font-semibold uppercase tracking-wider">
                                No teachers assigned to this department
                              </div>
                            )}
                        </div>
                    </div>
                </div>

                <div className="space-y-6">
                    <div className="flex justify-between items-center px-1">
                        <h4 className="text-[0.65rem] font-black uppercase tracking-[3px] text-text-muted">{terms.subjects} & Syllabi</h4>
                        <button 
                          onClick={() => openAddSubjectForDept(selectedDept.id)}
                          className="flex items-center gap-1 px-3 py-1.5 bg-primary text-white rounded-xl font-bold text-[0.6rem] uppercase tracking-wider hover:bg-primary/90 transition-all active:scale-95 shadow-sm"
                        >
                          <Plus size={12} />
                          Establish Unit
                        </button>
                    </div>
                    <div className="bg-card border border-border rounded-[2rem] overflow-hidden shadow-sm">
                        <div className="p-4 bg-muted/30 border-b border-border text-[0.6rem] font-black uppercase tracking-widest text-primary flex justify-between">
                            <span>Syllabus {terms.subject}</span>
                            <span>Direct Actions</span>
                        </div>
                        <div className="divide-y divide-border">
                            {selectedDept.subjects && selectedDept.subjects.length > 0 ? (
                              selectedDept.subjects.map((sub: any) => (
                                <div key={sub.id} className="p-4 flex items-center justify-between hover:bg-muted/50 transition-colors cursor-default">
                                    <div>
                                        <p className="text-sm font-bold text-text">{sub.name}</p>
                                        <div className="flex flex-wrap items-center gap-x-2 gap-y-1 mt-0.5">
                                            <p className="text-[0.6rem] font-black text-text-muted uppercase tracking-tight">Code: {sub.code || 'N/A'}</p>
                                            {sub.teacher_name && (
                                                <>
                                                    <span className="w-1 h-1 rounded-full bg-text-muted/30"></span>
                                                    <p className="text-[0.6rem] font-black text-emerald-500 uppercase tracking-widest">Teacher: {sub.teacher_name}</p>
                                                </>
                                            )}
                                        </div>
                                        {sub.syllabus_url && (
                                            <a 
                                                href={sub.syllabus_url} 
                                                target="_blank" 
                                                rel="noopener noreferrer" 
                                                className="inline-flex items-center gap-1 text-[0.6rem] font-black text-indigo-500 dark:text-indigo-400 hover:underline mt-1"
                                                onClick={e => e.stopPropagation()}
                                            >
                                                View Syllabus ({sub.syllabus_name || 'PDF'})
                                            </a>
                                        )}
                                    </div>
                                    <div className="flex items-center gap-2">
                                        <span className="text-[0.65rem] font-black uppercase tracking-wider px-2.5 py-1 rounded-full bg-primary/10 text-primary border border-primary/20 mr-1">
                                            {sub.class_name || 'Generic'}
                                        </span>
                                        <button 
                                            onClick={(e) => { e.stopPropagation(); openEditSubject(sub); }}
                                            className="p-1.5 bg-card rounded-lg border border-border text-text-muted hover:text-primary hover:border-primary transition-all shadow-sm"
                                        >
                                            <Edit2 size={12} />
                                        </button>
                                        <button 
                                            onClick={(e) => { e.stopPropagation(); deleteSubject(sub.id); }}
                                            className="p-1.5 bg-card rounded-lg border border-border text-text-muted hover:text-rose-500 hover:border-rose-100 transition-all shadow-sm"
                                        >
                                            <Trash2 size={12} />
                                        </button>
                                    </div>
                                </div>
                              ))
                            ) : (
                              <div className="p-8 text-center text-text-muted text-xs font-semibold uppercase tracking-wider">
                                No subjects registered in this department
                              </div>
                            )}
                        </div>
                    </div>
                </div>
            </div>

            <div className="p-10 border-t border-border bg-muted/50 shrink-0 flex flex-col sm:flex-row justify-between gap-4">
              <button
                onClick={() => deleteDepartment(selectedDept.id)}
                className="flex items-center justify-center gap-2 px-6 py-4 bg-card border border-border text-rose-500 rounded-2xl font-black text-[0.65rem] uppercase tracking-widest hover:bg-rose-50 dark:hover:bg-rose-500/10 hover:border-rose-100 transition-all shadow-sm"
              >
                <Trash2 size={16} /> Archive Department
              </button>
              <div className="flex gap-3">
                <button
                  onClick={() => setShowViewModal(false)}
                  className="flex-1 sm:flex-none px-12 py-4 bg-[#002147] hover:bg-black text-white rounded-2xl font-black text-[0.7rem] uppercase tracking-widest transition-all shadow-xl shadow-blue-900/10 active:scale-95"
                >
                  Exit Audit
                </button>
              </div>
            </div>
          </ModalBody>
        </Modal>
      )}

      {/* Subject Modal (Establish Unit) */}
      {showSubjectModal && (
        <Modal
          open={true}
          onClose={() => setShowSubjectModal(false)}
          title={editingSubjectId ? 'Modify Unit Record' : 'Establish Unit'}
          icon={Sparkles}
          maxWidth="max-w-xl"
          zIndex={150}
        >
          <ModalBody className="p-0">
            <div className="px-10 py-8 bg-muted/50 border-b border-border flex justify-between items-center relative overflow-hidden">
                <div className="absolute right-[-20px] top-[-20px] opacity-[0.03] rotate-12">
                    <Sparkles size={180} />
                </div>
              <div className="relative z-10">
                <h2 className="text-2xl font-black text-text tracking-tight uppercase">
                  {editingSubjectId ? 'Modify Unit Record' : 'Establish Unit'}
                </h2>
                <p className="text-xs font-bold text-text-muted uppercase tracking-widest mt-1">
                  {editingSubjectId ? 'Update academic unit details' : 'Configure academic structure'}
                </p>
              </div>
            </div>
            <form onSubmit={handleSubjectSubmit} className="p-10 space-y-6">
              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Unit Identifier (Name)</label>
                <input 
                  className="w-full bg-muted/50 border border-border rounded-2xl px-5 py-4 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all text-text dark:bg-background/50" 
                  value={subjectForm.name} 
                  onChange={e => setSubjectForm({...subjectForm, name: e.target.value})} 
                  placeholder="e.g., Quantum Mechanics" 
                  required 
                />
              </div>
              <div className="grid grid-cols-2 gap-6">
                <div className="space-y-1.5">
                  <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Unit Code (Auto-generated)</label>
                  <div className="w-full bg-muted/30 border border-border rounded-2xl px-5 py-4 text-sm font-semibold text-text-muted dark:bg-background/30 h-[54px] flex items-center">
                    {subjectForm.code || 'Pending name & section...'}
                  </div>
                </div>
                <SearchableSelect
                  label="Associate with Section"
                  placeholder="Select section..."
                  options={classes.map(c => ({ value: c.id, label: `${c.name} ${c.section ? `(${c.section})` : ''}` }))}
                  value={subjectForm.class_id}
                  onChange={val => setSubjectForm({...subjectForm, class_id: val})}
                />
              </div>
              
              <div className="grid grid-cols-2 gap-6">
                <SearchableSelect
                  label="Academic Department"
                  placeholder="Select department..."
                  options={departments.map(d => ({ value: d.id, label: d.name }))}
                  value={subjectForm.department_id}
                  onChange={val => setSubjectForm({...subjectForm, department_id: val})}
                />
                <SearchableSelect
                  label="Assign Teacher"
                  placeholder="Select teacher..."
                  options={teachers.map(t => ({ value: t.id, label: `${t.first_name} ${t.last_name}` }))}
                  value={subjectForm.teacher_id}
                  onChange={val => setSubjectForm({...subjectForm, teacher_id: val})}
                />
              </div>

              <div className="space-y-1.5">
                <label className="text-[0.6rem] font-black uppercase tracking-[2px] text-text-muted px-1">Upload Syllabus (Optional)</label>
                {subjectForm.syllabus_name && !deleteSyllabus ? (
                  <div className="flex items-center justify-between bg-muted/50 border border-border rounded-2xl p-4 dark:bg-background/50">
                    <span className="text-xs font-semibold text-text truncate max-w-[70%]">{subjectForm.syllabus_name}</span>
                    <button 
                      type="button" 
                      onClick={() => setDeleteSyllabus(true)} 
                      className="text-xs font-black uppercase text-rose-500 hover:text-rose-600 transition-colors"
                    >
                      Remove
                    </button>
                  </div>
                ) : (
                  <input 
                    type="file" 
                    accept=".pdf,.doc,.docx,.png,.jpg,.jpeg"
                    className="w-full bg-muted/50 border border-border rounded-2xl px-5 py-4 text-sm font-semibold focus:outline-none focus:ring-4 focus:ring-blue-500/5 focus:bg-card focus:border-primary transition-all text-text file:mr-4 file:py-2 file:px-4 file:rounded-xl file:border-0 file:text-xs file:font-semibold file:bg-primary/10 file:text-primary hover:file:bg-primary/20 cursor-pointer dark:bg-background/50"
                    onChange={e => {
                      if (e.target.files && e.target.files[0]) {
                        setSubjectForm({...subjectForm, syllabus: e.target.files[0], syllabus_name: e.target.files[0].name});
                        setDeleteSyllabus(false);
                      }
                    }} 
                  />
                )}
              </div>

              <button type="submit" className="w-full py-5 bg-primary hover:bg-primary/90 text-white font-black uppercase tracking-widest text-xs rounded-2xl transition-all shadow-xl active:scale-95 flex items-center justify-center gap-3">
                {editingSubjectId ? <CheckCircle2 size={18} /> : <Sparkles size={18} />}
                {editingSubjectId ? 'Finalize Unit Records' : 'Finalize Unit Records'}
              </button>
            </form>
          </ModalBody>
        </Modal>
      )}

      <style>{`
        .custom-scrollbar::-webkit-scrollbar { width: 4px; }
        .custom-scrollbar::-webkit-scrollbar-track { background: transparent; }
        .custom-scrollbar::-webkit-scrollbar-thumb { background: rgba(0, 71, 171, 0.1); border-radius: 10px; }
        .custom-scrollbar::-webkit-scrollbar-thumb:hover { background: rgba(0, 71, 171, 0.2); }
      `}</style>
    </div>
  );
}
