"use client";

import React, { useState } from "react";
import Link from "next/link";
import {
  Search,
  RotateCcw,
  Plus,
  Eye,
  Edit2,
  Trash2,
  ChevronRight,
  FileSpreadsheet,
  FileText,
  UserCheck,
  Mail,
  Phone,
  Building2,
  X,
  Save,
} from "lucide-react";
import { toast } from "sonner";

interface ExtendedFaculty {
  id: string;
  employeeId: string;
  name: string;
  designation: string;
  department: string;
  email: string;
  mobile: string;
  status: "Active" | "Inactive";
  weeklyTheoryHours: number;
  weeklyPracticalHours: number;
  totalWeeklyHours: number;
}

const initialDepartments = [
  "Food Production",
  "F&B Service",
  "Front Office",
  "Housekeeping",
  "Bakery & Confectionery",
];

const initialFaculty: ExtendedFaculty[] = [
  {
    id: "fac-101",
    employeeId: "EMP-041",
    name: "Chef Rajesh Sharma",
    designation: "Senior Lecturer & HOD Culinary",
    department: "Food Production",
    email: "rajesh.sharma@ihm.edu.in",
    mobile: "+91 98112 34567",
    status: "Active",
    weeklyTheoryHours: 2.0,
    weeklyPracticalHours: 16.0,
    totalWeeklyHours: 18.0,
  },
  {
    id: "fac-102",
    employeeId: "EMP-088",
    name: "Chef Amit Roy",
    designation: "Lecturer (Culinary Arts)",
    department: "Food Production",
    email: "amit.roy@ihm.edu.in",
    mobile: "+91 98112 34568",
    status: "Active",
    weeklyTheoryHours: 2.0,
    weeklyPracticalHours: 12.0,
    totalWeeklyHours: 14.0,
  },
  {
    id: "fac-103",
    employeeId: "EMP-056",
    name: "Prof. Ananya Sen",
    designation: "Assistant Professor & In-Charge F&B",
    department: "F&B Service",
    email: "ananya.sen@ihm.edu.in",
    mobile: "+91 98112 34569",
    status: "Active",
    weeklyTheoryHours: 4.0,
    weeklyPracticalHours: 8.0,
    totalWeeklyHours: 12.0,
  },
  {
    id: "fac-104",
    employeeId: "EMP-092",
    name: "Chef Vikram Singh",
    designation: "Master Baker & Lecturer",
    department: "Food Production",
    email: "vikram.singh@ihm.edu.in",
    mobile: "+91 98112 34570",
    status: "Active",
    weeklyTheoryHours: 0.0,
    weeklyPracticalHours: 16.0,
    totalWeeklyHours: 16.0,
  },
  {
    id: "fac-105",
    employeeId: "EMP-034",
    name: "Prof. Priya Nair",
    designation: "Senior Lecturer",
    department: "Front Office",
    email: "priya.nair@ihm.edu.in",
    mobile: "+91 98112 34571",
    status: "Active",
    weeklyTheoryHours: 6.0,
    weeklyPracticalHours: 6.0,
    totalWeeklyHours: 12.0,
  },
  {
    id: "fac-106",
    employeeId: "EMP-071",
    name: "Ms. Moumita Bose",
    designation: "Assistant Lecturer",
    department: "Housekeeping",
    email: "moumita.bose@ihm.edu.in",
    mobile: "+91 98112 34572",
    status: "Inactive",
    weeklyTheoryHours: 4.0,
    weeklyPracticalHours: 6.0,
    totalWeeklyHours: 10.0,
  },
];

export default function FacultyDirectoryPage() {
  const [facultyList, setFacultyList] = useState<ExtendedFaculty[]>(initialFaculty);
  const [departments, setDepartments] = useState<string[]>(initialDepartments);

  // Filters
  const [selectedDept, setSelectedDept] = useState("All Departments");
  const [selectedDesignation, setSelectedDesignation] = useState("All Designations");
  const [selectedStatus, setSelectedStatus] = useState("All Status");
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedRows, setSelectedRows] = useState<string[]>([]);
  const [pageSize, setPageSize] = useState("10 per page");

  // Faculty Modal State
  const [isFacultyModalOpen, setIsFacultyModalOpen] = useState(false);
  const [facultyModalMode, setFacultyModalMode] = useState<"create" | "edit" | "view">("create");
  const [editingFacultyId, setEditingFacultyId] = useState<string | null>(null);
  const [viewingFaculty, setViewingFaculty] = useState<ExtendedFaculty | null>(null);

  // Faculty Form Fields
  const [facultyFormData, setFacultyFormData] = useState({
    employeeId: "",
    name: "",
    designation: "Lecturer",
    department: "Food Production",
    email: "",
    mobile: "",
    weeklyTheoryHours: 2,
    weeklyPracticalHours: 12,
    status: "Active" as "Active" | "Inactive",
  });

  // Department Modal State
  const [isDeptModalOpen, setIsDeptModalOpen] = useState(false);
  const [newDeptName, setNewDeptName] = useState("");
  const [newDeptCode, setNewDeptCode] = useState("");
  const [newDeptHod, setNewDeptHod] = useState("");

  const filteredFaculty = facultyList.filter((f) => {
    const matchesDept =
      selectedDept === "All Departments" || f.department === selectedDept;
    const matchesDesig =
      selectedDesignation === "All Designations" ||
      f.designation.includes(selectedDesignation);
    const matchesStatus =
      selectedStatus === "All Status" || f.status === selectedStatus;
    const matchesSearch =
      searchQuery === "" ||
      f.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      f.employeeId.toLowerCase().includes(searchQuery.toLowerCase()) ||
      f.email.toLowerCase().includes(searchQuery.toLowerCase()) ||
      f.department.toLowerCase().includes(searchQuery.toLowerCase());
    return matchesDept && matchesDesig && matchesStatus && matchesSearch;
  });

  const handleSelectAll = () => {
    if (selectedRows.length === filteredFaculty.length && filteredFaculty.length > 0) {
      setSelectedRows([]);
    } else {
      setSelectedRows(filteredFaculty.map((f) => f.id));
    }
  };

  const handleRowSelect = (id: string) => {
    setSelectedRows((prev) =>
      prev.includes(id) ? prev.filter((r) => r !== id) : [...prev, id]
    );
  };

  const handleResetFilters = () => {
    setSelectedDept("All Departments");
    setSelectedDesignation("All Designations");
    setSelectedStatus("All Status");
    setSearchQuery("");
  };

  const handleDelete = (id: string) => {
    setFacultyList((prev) => prev.filter((f) => f.id !== id));
    toast.success("Faculty member record removed successfully.");
  };

  // Faculty Modal handlers
  const openCreateFacultyModal = () => {
    setFacultyModalMode("create");
    setEditingFacultyId(null);
    setViewingFaculty(null);
    setFacultyFormData({
      employeeId: "",
      name: "",
      designation: "Lecturer",
      department: departments[0] || "Food Production",
      email: "",
      mobile: "",
      weeklyTheoryHours: 2,
      weeklyPracticalHours: 12,
      status: "Active",
    });
    setIsFacultyModalOpen(true);
  };

  const openEditFacultyModal = (faculty: ExtendedFaculty) => {
    setFacultyModalMode("edit");
    setEditingFacultyId(faculty.id);
    setViewingFaculty(null);
    setFacultyFormData({
      employeeId: faculty.employeeId,
      name: faculty.name,
      designation: faculty.designation,
      department: faculty.department,
      email: faculty.email,
      mobile: faculty.mobile,
      weeklyTheoryHours: faculty.weeklyTheoryHours,
      weeklyPracticalHours: faculty.weeklyPracticalHours,
      status: faculty.status,
    });
    setIsFacultyModalOpen(true);
  };

  const openViewFacultyModal = (faculty: ExtendedFaculty) => {
    setViewingFaculty(faculty);
    setFacultyModalMode("view");
    setIsFacultyModalOpen(true);
  };

  const handleSaveFaculty = (e: React.FormEvent) => {
    e.preventDefault();

    if (!facultyFormData.name.trim() || !facultyFormData.employeeId.trim()) {
      toast.error("Please enter Employee ID and Faculty Name.");
      return;
    }

    const totalHours =
      Number(facultyFormData.weeklyTheoryHours) + Number(facultyFormData.weeklyPracticalHours);

    if (editingFacultyId) {
      setFacultyList((prev) =>
        prev.map((f) =>
          f.id === editingFacultyId
            ? {
                ...f,
                employeeId: facultyFormData.employeeId.toUpperCase(),
                name: facultyFormData.name,
                designation: facultyFormData.designation,
                department: facultyFormData.department,
                email: facultyFormData.email,
                mobile: facultyFormData.mobile,
                weeklyTheoryHours: Number(facultyFormData.weeklyTheoryHours),
                weeklyPracticalHours: Number(facultyFormData.weeklyPracticalHours),
                totalWeeklyHours: totalHours,
                status: facultyFormData.status,
              }
            : f
        )
      );
      toast.success("Faculty profile updated successfully.");
    } else {
      const newFaculty: ExtendedFaculty = {
        id: `fac-${Date.now()}`,
        employeeId: facultyFormData.employeeId.toUpperCase(),
        name: facultyFormData.name,
        designation: facultyFormData.designation,
        department: facultyFormData.department,
        email:
          facultyFormData.email ||
          `${facultyFormData.name.toLowerCase().replace(/[^a-z]/g, "")}@ihm.edu.in`,
        mobile: facultyFormData.mobile || "+91 98000 00000",
        weeklyTheoryHours: Number(facultyFormData.weeklyTheoryHours),
        weeklyPracticalHours: Number(facultyFormData.weeklyPracticalHours),
        totalWeeklyHours: totalHours,
        status: facultyFormData.status,
      };
      setFacultyList((prev) => [newFaculty, ...prev]);
      toast.success("New faculty member enrolled.");
    }

    setIsFacultyModalOpen(false);
  };

  // Department Modal handlers
  const openDeptModal = () => {
    setNewDeptName("");
    setNewDeptCode("");
    setNewDeptHod("");
    setIsDeptModalOpen(true);
  };

  const handleSaveDepartment = (e: React.FormEvent) => {
    e.preventDefault();

    if (!newDeptName.trim()) {
      toast.error("Please enter a department name.");
      return;
    }

    if (departments.includes(newDeptName.trim())) {
      toast.error("This department already exists.");
      return;
    }

    setDepartments((prev) => [...prev, newDeptName.trim()]);
    toast.success(`Department "${newDeptName.trim()}" created successfully.`);
    setIsDeptModalOpen(false);
  };

  return (
    <div className="space-y-5 font-sans">
      {/* ============================================================ */}
      {/* 1. TOP HEADER & BREADCRUMB                                   */}
      {/* ============================================================ */}
      <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
        <div>
          <nav className="flex items-center gap-1.5 text-[13px] text-[#64748B] mb-1 font-medium font-sans">
            <Link href="/admin/dashboard" className="hover:text-[#1769E8] hover:underline">
              Home
            </Link>
            <ChevronRight className="w-3.5 h-3.5 text-[#94A3B8]" />
            <span>Faculty Management</span>
            <ChevronRight className="w-3.5 h-3.5 text-[#94A3B8]" />
            <span className="text-[#071A4D] font-semibold">Faculty List</span>
          </nav>

          <h1 className="text-3xl font-bold font-heading text-[#071A4D] tracking-tight">
            Faculty Directory
          </h1>
          <p className="text-[15px] text-[#64748B] mt-1 font-normal font-sans">
            Manage academic instructors, designations, department allocations, and teaching load.
          </p>
        </div>

        {/* Separate Top Action Buttons in this Main Category */}
        <div className="flex items-center gap-2.5 flex-wrap font-sans">
          <button
            onClick={() => toast.success("Exporting Faculty Directory to CSV...")}
            className="inline-flex items-center gap-1.5 px-3.5 py-2 text-xs font-semibold text-[#071A4D] bg-white border border-[#E5EAF0] rounded-lg hover:bg-slate-50 transition-colors shadow-2xs cursor-pointer"
          >
            <FileSpreadsheet className="w-4 h-4 text-emerald-600" />
            <span>Export</span>
          </button>

          <button
            onClick={openDeptModal}
            className="inline-flex items-center gap-1.5 px-3.5 py-2 text-xs font-semibold text-[#071A4D] bg-white border border-[#E5EAF0] rounded-lg hover:bg-slate-50 transition-colors shadow-2xs cursor-pointer"
          >
            <Building2 className="w-4 h-4 text-[#1769E8]" />
            <span>+ Add Department</span>
          </button>

          <Link
            href="/admin/people/faculty/register"
            className="inline-flex items-center gap-1.5 px-4 py-2 text-xs font-semibold text-white bg-[#1769E8] hover:bg-[#1257C7] rounded-lg shadow-sm transition-colors cursor-pointer"
          >
            <Plus className="w-4 h-4" />
            <span>+ Faculty Registration</span>
          </Link>
        </div>
      </div>

      {/* ============================================================ */}
      {/* 2. FILTER AND SEARCH BAR                                     */}
      {/* ============================================================ */}
      <div className="p-4 rounded-xl bg-white border border-[#E5EAF0] shadow-xs flex flex-col lg:flex-row items-stretch lg:items-center justify-between gap-3 font-sans">
        <div className="flex flex-wrap items-center gap-2.5 flex-1">
          {/* Department Filter (Dynamic) */}
          <div className="flex flex-col">
            <label className="text-[10px] font-bold text-[#64748B] mb-0.5 uppercase tracking-wider">
              Department
            </label>
            <select
              value={selectedDept}
              onChange={(e) => setSelectedDept(e.target.value)}
              className="h-9 px-3 rounded-lg border border-[#D8E0EA] bg-white text-xs font-medium text-[#334155] focus:outline-none focus:border-[#1769E8] focus:ring-1 focus:ring-[#1769E8]/20 cursor-pointer"
            >
              <option>All Departments</option>
              {departments.map((dept) => (
                <option key={dept} value={dept}>
                  {dept}
                </option>
              ))}
            </select>
          </div>

          {/* Designation Filter */}
          <div className="flex flex-col">
            <label className="text-[10px] font-bold text-[#64748B] mb-0.5 uppercase tracking-wider">
              Designation
            </label>
            <select
              value={selectedDesignation}
              onChange={(e) => setSelectedDesignation(e.target.value)}
              className="h-9 px-3 rounded-lg border border-[#D8E0EA] bg-white text-xs font-medium text-[#334155] focus:outline-none focus:border-[#1769E8] focus:ring-1 focus:ring-[#1769E8]/20 cursor-pointer"
            >
              <option>All Designations</option>
              <option>Senior Lecturer &amp; HOD</option>
              <option>Senior Lecturer</option>
              <option>Lecturer</option>
              <option>Assistant Professor</option>
              <option>Assistant Lecturer</option>
            </select>
          </div>

          {/* Status Filter */}
          <div className="flex flex-col">
            <label className="text-[10px] font-bold text-[#64748B] mb-0.5 uppercase tracking-wider">
              Status
            </label>
            <select
              value={selectedStatus}
              onChange={(e) => setSelectedStatus(e.target.value)}
              className="h-9 px-3 rounded-lg border border-[#D8E0EA] bg-white text-xs font-medium text-[#334155] focus:outline-none focus:border-[#1769E8] focus:ring-1 focus:ring-[#1769E8]/20 cursor-pointer"
            >
              <option>All Status</option>
              <option>Active</option>
              <option>Inactive</option>
            </select>
          </div>

          {/* Search Box */}
          <div className="flex flex-col flex-1 min-w-[220px]">
            <label className="text-[10px] font-bold text-[#64748B] mb-0.5 uppercase tracking-wider opacity-0">
              Search
            </label>
            <div className="relative">
              <Search className="w-4 h-4 text-[#94A3B8] absolute left-3 top-1/2 -translate-y-1/2" />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="Search faculty name, employee ID, email..."
                className="h-9 w-full rounded-lg border border-[#D8E0EA] bg-white pl-9 pr-3 text-xs text-[#334155] placeholder:text-[#94A3B8] focus:outline-none focus:border-[#1769E8] focus:ring-1 focus:ring-[#1769E8]/20"
              />
            </div>
          </div>
        </div>

        {/* Action Buttons */}
        <div className="flex items-end gap-2 shrink-0 pt-3 lg:pt-0 font-sans">
          <button
            onClick={() => {}}
            className="h-9 px-4 rounded-lg bg-[#1769E8] hover:bg-[#1257C7] text-white text-xs font-semibold flex items-center gap-1.5 shadow-xs transition-colors cursor-pointer"
          >
            <Search className="w-3.5 h-3.5" />
            <span>Search</span>
          </button>

          <button
            onClick={handleResetFilters}
            className="h-9 px-4 rounded-lg border border-[#E5EAF0] hover:bg-slate-50 text-[#334155] text-xs font-semibold flex items-center gap-1.5 transition-colors shadow-2xs cursor-pointer"
          >
            <RotateCcw className="w-3.5 h-3.5 text-[#64748B]" />
            <span>Reset</span>
          </button>
        </div>
      </div>

      {/* ============================================================ */}
      {/* 3. FULL WIDTH SERIAL TABLE - ALL DETAILS IN A LINE           */}
      {/* ============================================================ */}
      <div className="rounded-xl bg-white border border-[#E5EAF0] shadow-xs overflow-hidden">
        {/* Table Header Controls */}
        <div className="p-4 border-b border-[#E5EAF0] flex items-center justify-between">
          <div className="flex items-center gap-2">
            <UserCheck className="w-4 h-4 text-[#1769E8]" />
            <h2 className="text-sm font-bold font-heading text-[#071A4D]">
              Faculty Directory ({filteredFaculty.length})
            </h2>
          </div>

          <select
            value={pageSize}
            onChange={(e) => setPageSize(e.target.value)}
            className="h-8 px-2.5 rounded-lg border border-[#D8E0EA] bg-white text-xs text-[#64748B] focus:outline-none focus:border-[#1769E8] cursor-pointer"
          >
            <option>10 per page</option>
            <option>25 per page</option>
            <option>50 per page</option>
          </select>
        </div>

        {/* Table Data */}
        <div className="overflow-x-auto">
          <table className="w-full text-left text-xs border-collapse">
            <thead>
              <tr className="bg-[#F8FAFC] border-b border-[#E5EAF0] text-[#64748B] uppercase tracking-wider font-bold text-[11px] whitespace-nowrap">
                <th className="py-3 px-3.5 text-center w-10">
                  <input
                    type="checkbox"
                    checked={
                      selectedRows.length === filteredFaculty.length &&
                      filteredFaculty.length > 0
                    }
                    onChange={handleSelectAll}
                    className="rounded border-[#D8E0EA] text-[#1769E8] focus:ring-[#1769E8] cursor-pointer"
                  />
                </th>
                <th className="py-3 px-2 text-center w-10">#</th>
                <th className="py-3 px-4">Employee ID</th>
                <th className="py-3 px-4">Faculty Member</th>
                <th className="py-3 px-4">Department</th>
                <th className="py-3 px-4">Email</th>
                <th className="py-3 px-4">Mobile</th>
                <th className="py-3 px-4 text-center">Workload (T / P / Total)</th>
                <th className="py-3 px-4 text-center">Status</th>
                <th className="py-3 px-4 text-center">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[#E5EAF0] text-[#334155]">
              {filteredFaculty.length === 0 ? (
                <tr>
                  <td colSpan={10} className="py-12 text-center text-slate-400">
                    No faculty members match your query.
                  </td>
                </tr>
              ) : (
                filteredFaculty.map((f, idx) => {
                  const isSelected = selectedRows.includes(f.id);
                  return (
                    <tr
                      key={f.id}
                      className={`hover:bg-[#F8FAFC] transition-colors whitespace-nowrap ${
                        isSelected ? "bg-blue-50/40" : ""
                      }`}
                    >
                      <td className="py-3.5 px-3.5 text-center">
                        <input
                          type="checkbox"
                          checked={isSelected}
                          onChange={() => handleRowSelect(f.id)}
                          className="rounded border-[#D8E0EA] text-[#1769E8] focus:ring-[#1769E8] cursor-pointer"
                        />
                      </td>
                      <td className="py-3.5 px-2 text-center text-slate-400 font-medium">
                        {idx + 1}
                      </td>
                      <td className="py-3.5 px-4 font-mono font-bold text-[#1769E8]">
                        <span className="bg-blue-50 border border-blue-100 px-2 py-0.5 rounded text-[11px]">
                          {f.employeeId}
                        </span>
                      </td>
                      <td className="py-3.5 px-4">
                        <div>
                          <span className="font-bold text-[#071A4D] block text-xs">
                            {f.name}
                          </span>
                          <span className="text-[11px] text-[#64748B] block mt-0.5">
                            {f.designation}
                          </span>
                        </div>
                      </td>
                      <td className="py-3.5 px-4">
                        <span className="inline-flex items-center px-2 py-0.5 rounded-md text-[11px] font-medium bg-slate-100 text-slate-700">
                          {f.department}
                        </span>
                      </td>
                      <td className="py-3.5 px-4 text-[#64748B]">
                        <div className="flex items-center gap-1.5">
                          <Mail className="w-3.5 h-3.5 text-slate-400" />
                          <span>{f.email}</span>
                        </div>
                      </td>
                      <td className="py-3.5 px-4 text-[#64748B]">
                        <div className="flex items-center gap-1.5">
                          <Phone className="w-3.5 h-3.5 text-slate-400" />
                          <span>{f.mobile}</span>
                        </div>
                      </td>
                      <td className="py-3.5 px-4 text-center">
                        <span className="font-mono font-bold text-[#071A4D]">
                          {f.totalWeeklyHours} hrs/wk
                        </span>
                        <span className="text-[10px] text-[#64748B] block">
                          {f.weeklyTheoryHours}h Th + {f.weeklyPracticalHours}h Pr
                        </span>
                      </td>
                      <td className="py-3.5 px-4 text-center">
                        {f.status === "Active" ? (
                          <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[11px] font-semibold bg-[#DCFCE7] text-[#15803D]">
                            <span className="w-1.5 h-1.5 rounded-full bg-[#15803D]"></span>
                            Active
                          </span>
                        ) : (
                          <span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-[11px] font-semibold bg-[#FEE2E2] text-[#DC2626]">
                            <span className="w-1.5 h-1.5 rounded-full bg-[#DC2626]"></span>
                            Inactive
                          </span>
                        )}
                      </td>
                      <td className="py-3.5 px-4 text-center">
                        <div className="flex items-center justify-center gap-1.5">
                          <button
                            onClick={() => openViewFacultyModal(f)}
                            className="p-1.5 rounded-lg text-[#1769E8] hover:bg-blue-50 transition-colors"
                            title="View Faculty Profile"
                          >
                            <Eye className="w-4 h-4" />
                          </button>

                          <button
                            onClick={() => openEditFacultyModal(f)}
                            className="p-1.5 rounded-lg text-[#1769E8] hover:bg-blue-50 transition-colors"
                            title="Edit Faculty"
                          >
                            <Edit2 className="w-4 h-4" />
                          </button>

                          <button
                            onClick={() => handleDelete(f.id)}
                            className="p-1.5 rounded-lg text-[#DC2626] hover:bg-red-50 transition-colors"
                            title="Delete Faculty"
                          >
                            <Trash2 className="w-4 h-4" />
                          </button>
                        </div>
                      </td>
                    </tr>
                  );
                })
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination Footer */}
        <div className="p-3.5 px-4 border-t border-[#E5EAF0] flex items-center justify-between text-xs text-[#64748B]">
          <div>
            Showing 1 to {filteredFaculty.length} of {facultyList.length} instructors
          </div>
          <div className="flex items-center gap-1">
            <button
              disabled
              className="px-2.5 py-1 rounded border border-[#E5EAF0] text-slate-300 cursor-not-allowed"
            >
              &lt;
            </button>
            <button className="px-3 py-1 rounded bg-[#1769E8] text-white font-bold">
              1
            </button>
            <button
              disabled
              className="px-2.5 py-1 rounded border border-[#E5EAF0] text-slate-300 cursor-not-allowed"
            >
              &gt;
            </button>
          </div>
        </div>
      </div>

      {/* ============================================================ */}
      {/* 4. POPUP MODAL: CREATE / EDIT / VIEW FACULTY                 */}
      {/* ============================================================ */}
      {isFacultyModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-xs p-4 animate-in fade-in duration-150">
          <div className="w-full max-w-lg bg-white rounded-2xl shadow-2xl border border-[#E5EAF0] overflow-hidden flex flex-col max-h-[90vh]">
            {/* Header */}
            <div className="px-6 py-4 border-b border-[#E5EAF0] flex items-center justify-between bg-slate-50/60">
              <div className="flex items-center gap-2.5">
                <div className="w-9 h-9 rounded-xl bg-blue-50 text-[#1769E8] flex items-center justify-center">
                  <UserCheck className="w-5 h-5" />
                </div>
                <div>
                  <h3 className="font-heading font-bold text-base text-[#071A4D]">
                    {facultyModalMode === "create" && "Add New Faculty"}
                    {facultyModalMode === "edit" && "Edit Faculty Profile"}
                    {facultyModalMode === "view" && "Faculty Profile Overview"}
                  </h3>
                  <p className="text-[12px] text-[#64748B]">
                    {facultyModalMode === "create" && "Register an academic instructor or culinary chef."}
                    {facultyModalMode === "edit" && "Update faculty contact and workload details."}
                    {facultyModalMode === "view" && "Complete academic profile and contact specifications."}
                  </p>
                </div>
              </div>
              <button
                onClick={() => setIsFacultyModalOpen(false)}
                className="w-8 h-8 rounded-lg text-slate-400 hover:text-slate-700 hover:bg-slate-100 flex items-center justify-center transition-colors cursor-pointer"
              >
                <X className="w-4 h-4" />
              </button>
            </div>

            {/* Content */}
            <div className="p-6 overflow-y-auto space-y-4">
              {facultyModalMode === "view" && viewingFaculty ? (
                <div className="space-y-4 text-xs">
                  <div className="grid grid-cols-2 gap-4 p-4 rounded-xl bg-slate-50 border border-slate-100">
                    <div>
                      <span className="text-[10px] uppercase font-bold text-[#64748B] block">Employee ID</span>
                      <span className="text-sm font-bold font-mono text-[#1769E8]">{viewingFaculty.employeeId}</span>
                    </div>
                    <div>
                      <span className="text-[10px] uppercase font-bold text-[#64748B] block">Department</span>
                      <span className="text-sm font-semibold text-[#071A4D]">{viewingFaculty.department}</span>
                    </div>
                    <div className="col-span-2">
                      <span className="text-[10px] uppercase font-bold text-[#64748B] block">Full Name</span>
                      <span className="text-base font-bold text-[#071A4D]">{viewingFaculty.name}</span>
                      <span className="text-xs text-[#64748B] block">{viewingFaculty.designation}</span>
                    </div>
                    <div>
                      <span className="text-[10px] uppercase font-bold text-[#64748B] block">Email</span>
                      <span className="text-xs text-[#334155]">{viewingFaculty.email}</span>
                    </div>
                    <div>
                      <span className="text-[10px] uppercase font-bold text-[#64748B] block">Mobile</span>
                      <span className="text-xs text-[#334155]">{viewingFaculty.mobile}</span>
                    </div>
                    <div>
                      <span className="text-[10px] uppercase font-bold text-[#64748B] block">Weekly Teaching Load</span>
                      <span className="text-xs font-bold text-[#071A4D]">
                        {viewingFaculty.totalWeeklyHours} Hours/Week ({viewingFaculty.weeklyTheoryHours}h Th / {viewingFaculty.weeklyPracticalHours}h Pr)
                      </span>
                    </div>
                    <div>
                      <span className="text-[10px] uppercase font-bold text-[#64748B] block">Status</span>
                      <span
                        className={`inline-block mt-0.5 px-2.5 py-0.5 rounded-full font-semibold text-[10px] ${
                          viewingFaculty.status === "Active"
                            ? "bg-[#DCFCE7] text-[#15803D]"
                            : "bg-[#FEE2E2] text-[#DC2626]"
                        }`}
                      >
                        {viewingFaculty.status}
                      </span>
                    </div>
                  </div>
                </div>
              ) : (
                <form id="faculty-form" onSubmit={handleSaveFaculty} className="space-y-4">
                  {/* Employee ID & Department */}
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="block text-xs font-bold text-[#334155] mb-1">
                        Employee ID <span className="text-[#DC2626]">*</span>
                      </label>
                      <input
                        type="text"
                        required
                        value={facultyFormData.employeeId}
                        onChange={(e) =>
                          setFacultyFormData({ ...facultyFormData, employeeId: e.target.value })
                        }
                        placeholder="e.g. EMP-045"
                        className="h-10 w-full px-3 text-xs uppercase font-mono rounded-lg border border-[#D8E0EA] bg-white text-[#334155] placeholder:text-[#94A3B8] focus:outline-none focus:border-[#1769E8] focus:ring-1 focus:ring-[#1769E8]/20"
                      />
                    </div>
                    <div>
                      <label className="block text-xs font-bold text-[#334155] mb-1">
                        Department <span className="text-[#DC2626]">*</span>
                      </label>
                      <select
                        value={facultyFormData.department}
                        onChange={(e) =>
                          setFacultyFormData({ ...facultyFormData, department: e.target.value })
                        }
                        className="h-10 w-full px-3 text-xs rounded-lg border border-[#D8E0EA] bg-white text-[#334155] focus:outline-none focus:border-[#1769E8] focus:ring-1 focus:ring-[#1769E8]/20 cursor-pointer"
                      >
                        {departments.map((dept) => (
                          <option key={dept} value={dept}>
                            {dept}
                          </option>
                        ))}
                      </select>
                    </div>
                  </div>

                  {/* Name */}
                  <div>
                    <label className="block text-xs font-bold text-[#334155] mb-1">
                      Faculty Full Name <span className="text-[#DC2626]">*</span>
                    </label>
                    <input
                      type="text"
                      required
                      value={facultyFormData.name}
                      onChange={(e) =>
                        setFacultyFormData({ ...facultyFormData, name: e.target.value })
                      }
                      placeholder="e.g. Chef Anupam Roy"
                      className="h-10 w-full px-3 text-xs rounded-lg border border-[#D8E0EA] bg-white text-[#334155] placeholder:text-[#94A3B8] focus:outline-none focus:border-[#1769E8] focus:ring-1 focus:ring-[#1769E8]/20"
                    />
                  </div>

                  {/* Designation */}
                  <div>
                    <label className="block text-xs font-bold text-[#334155] mb-1">
                      Designation
                    </label>
                    <select
                      value={facultyFormData.designation}
                      onChange={(e) =>
                        setFacultyFormData({ ...facultyFormData, designation: e.target.value })
                      }
                      className="h-10 w-full px-3 text-xs rounded-lg border border-[#D8E0EA] bg-white text-[#334155] focus:outline-none focus:border-[#1769E8] focus:ring-1 focus:ring-[#1769E8]/20 cursor-pointer"
                    >
                      <option>Senior Lecturer &amp; HOD</option>
                      <option>Senior Lecturer</option>
                      <option>Lecturer</option>
                      <option>Assistant Professor</option>
                      <option>Assistant Lecturer</option>
                      <option>Chef Instructor</option>
                    </select>
                  </div>

                  {/* Contact */}
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="block text-xs font-bold text-[#334155] mb-1">
                        Email Address
                      </label>
                      <input
                        type="email"
                        value={facultyFormData.email}
                        onChange={(e) =>
                          setFacultyFormData({ ...facultyFormData, email: e.target.value })
                        }
                        placeholder="email@ihm.edu.in"
                        className="h-10 w-full px-3 text-xs rounded-lg border border-[#D8E0EA] bg-white text-[#334155] focus:outline-none focus:border-[#1769E8] focus:ring-1 focus:ring-[#1769E8]/20"
                      />
                    </div>
                    <div>
                      <label className="block text-xs font-bold text-[#334155] mb-1">
                        Mobile Phone
                      </label>
                      <input
                        type="text"
                        value={facultyFormData.mobile}
                        onChange={(e) =>
                          setFacultyFormData({ ...facultyFormData, mobile: e.target.value })
                        }
                        placeholder="+91 98000 00000"
                        className="h-10 w-full px-3 text-xs rounded-lg border border-[#D8E0EA] bg-white text-[#334155] focus:outline-none focus:border-[#1769E8] focus:ring-1 focus:ring-[#1769E8]/20"
                      />
                    </div>
                  </div>

                  {/* Workload Theory & Practical */}
                  <div className="grid grid-cols-2 gap-3">
                    <div>
                      <label className="block text-xs font-bold text-[#334155] mb-1">
                        Theory Load (Hrs/Wk)
                      </label>
                      <input
                        type="number"
                        min="0"
                        max="30"
                        value={facultyFormData.weeklyTheoryHours}
                        onChange={(e) =>
                          setFacultyFormData({
                            ...facultyFormData,
                            weeklyTheoryHours: parseFloat(e.target.value) || 0,
                          })
                        }
                        className="h-10 w-full px-3 text-xs rounded-lg border border-[#D8E0EA] bg-white text-[#334155] focus:outline-none focus:border-[#1769E8] focus:ring-1 focus:ring-[#1769E8]/20 font-mono"
                      />
                    </div>
                    <div>
                      <label className="block text-xs font-bold text-[#334155] mb-1">
                        Practical Load (Hrs/Wk)
                      </label>
                      <input
                        type="number"
                        min="0"
                        max="40"
                        value={facultyFormData.weeklyPracticalHours}
                        onChange={(e) =>
                          setFacultyFormData({
                            ...facultyFormData,
                            weeklyPracticalHours: parseFloat(e.target.value) || 0,
                          })
                        }
                        className="h-10 w-full px-3 text-xs rounded-lg border border-[#D8E0EA] bg-white text-[#334155] focus:outline-none focus:border-[#1769E8] focus:ring-1 focus:ring-[#1769E8]/20 font-mono"
                      />
                    </div>
                  </div>

                  {/* Status */}
                  <div>
                    <label className="block text-xs font-bold text-[#334155] mb-2">
                      Status
                    </label>
                    <div className="flex items-center gap-5 text-xs">
                      <label className="flex items-center gap-1.5 cursor-pointer text-[#334155]">
                        <input
                          type="radio"
                          name="facStatus"
                          checked={facultyFormData.status === "Active"}
                          onChange={() =>
                            setFacultyFormData({ ...facultyFormData, status: "Active" })
                          }
                          className="text-[#1769E8] focus:ring-[#1769E8]"
                        />
                        <span className="font-medium">Active</span>
                      </label>

                      <label className="flex items-center gap-1.5 cursor-pointer text-[#334155]">
                        <input
                          type="radio"
                          name="facStatus"
                          checked={facultyFormData.status === "Inactive"}
                          onChange={() =>
                            setFacultyFormData({ ...facultyFormData, status: "Inactive" })
                          }
                          className="text-[#1769E8] focus:ring-[#1769E8]"
                        />
                        <span className="font-medium">Inactive</span>
                      </label>
                    </div>
                  </div>
                </form>
              )}
            </div>

            {/* Footer */}
            <div className="px-6 py-3.5 border-t border-[#E5EAF0] flex items-center justify-end gap-2.5 bg-slate-50/50">
              <button
                type="button"
                onClick={() => setIsFacultyModalOpen(false)}
                className="px-4 py-2 text-xs font-semibold text-[#64748B] bg-white hover:bg-slate-100 border border-[#E5EAF0] rounded-lg transition-colors cursor-pointer"
              >
                {facultyModalMode === "view" ? "Close" : "Cancel"}
              </button>

              {facultyModalMode !== "view" && (
                <button
                  type="submit"
                  form="faculty-form"
                  className="px-5 py-2 text-xs font-bold text-white bg-[#1769E8] hover:bg-[#1257C7] rounded-lg transition-colors flex items-center gap-1.5 shadow-xs cursor-pointer"
                >
                  <Save className="w-3.5 h-3.5" />
                  <span>
                    {facultyModalMode === "create" ? "Add Faculty" : "Save Changes"}
                  </span>
                </button>
              )}
            </div>
          </div>
        </div>
      )}

      {/* ============================================================ */}
      {/* 5. POPUP MODAL: ADD NEW DEPARTMENT                           */}
      {/* ============================================================ */}
      {isDeptModalOpen && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-xs p-4 animate-in fade-in duration-150">
          <div className="w-full max-w-md bg-white rounded-2xl shadow-2xl border border-[#E5EAF0] overflow-hidden flex flex-col">
            {/* Header */}
            <div className="px-6 py-4 border-b border-[#E5EAF0] flex items-center justify-between bg-slate-50/60">
              <div className="flex items-center gap-2.5">
                <div className="w-9 h-9 rounded-xl bg-blue-50 text-[#1769E8] flex items-center justify-center">
                  <Building2 className="w-5 h-5" />
                </div>
                <div>
                  <h3 className="font-heading font-bold text-base text-[#071A4D]">
                    Add New Department
                  </h3>
                  <p className="text-[12px] text-[#64748B]">
                    Register a new academic department or school.
                  </p>
                </div>
              </div>
              <button
                onClick={() => setIsDeptModalOpen(false)}
                className="w-8 h-8 rounded-lg text-slate-400 hover:text-slate-700 hover:bg-slate-100 flex items-center justify-center transition-colors cursor-pointer"
              >
                <X className="w-4 h-4" />
              </button>
            </div>

            {/* Form */}
            <form onSubmit={handleSaveDepartment} className="p-6 space-y-4">
              <div>
                <label className="block text-xs font-bold text-[#334155] mb-1">
                  Department Name <span className="text-[#DC2626]">*</span>
                </label>
                <input
                  type="text"
                  required
                  value={newDeptName}
                  onChange={(e) => setNewDeptName(e.target.value)}
                  placeholder="e.g. Food Production, Allied Hospitality"
                  className="h-10 w-full px-3 text-xs rounded-lg border border-[#D8E0EA] bg-white text-[#334155] placeholder:text-[#94A3B8] focus:outline-none focus:border-[#1769E8] focus:ring-1 focus:ring-[#1769E8]/20"
                />
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block text-xs font-bold text-[#334155] mb-1">
                    Department Code
                  </label>
                  <input
                    type="text"
                    value={newDeptCode}
                    onChange={(e) => setNewDeptCode(e.target.value)}
                    placeholder="e.g. FP, FBS, FO"
                    className="h-10 w-full px-3 text-xs uppercase font-mono rounded-lg border border-[#D8E0EA] bg-white text-[#334155] placeholder:text-[#94A3B8] focus:outline-none focus:border-[#1769E8] focus:ring-1 focus:ring-[#1769E8]/20"
                  />
                </div>
                <div>
                  <label className="block text-xs font-bold text-[#334155] mb-1">
                    HOD / In-Charge
                  </label>
                  <input
                    type="text"
                    value={newDeptHod}
                    onChange={(e) => setNewDeptHod(e.target.value)}
                    placeholder="e.g. Chef Rajesh Sharma"
                    className="h-10 w-full px-3 text-xs rounded-lg border border-[#D8E0EA] bg-white text-[#334155] placeholder:text-[#94A3B8] focus:outline-none focus:border-[#1769E8] focus:ring-1 focus:ring-[#1769E8]/20"
                  />
                </div>
              </div>

              {/* Existing Departments Preview */}
              <div>
                <span className="text-[10px] font-bold text-[#64748B] uppercase tracking-wider block mb-1.5">
                  Currently Active Departments ({departments.length})
                </span>
                <div className="flex flex-wrap gap-1.5 p-2.5 rounded-lg bg-slate-50 border border-slate-100 max-h-24 overflow-y-auto">
                  {departments.map((d) => (
                    <span
                      key={d}
                      className="px-2 py-0.5 rounded text-[11px] font-medium bg-white border border-slate-200 text-slate-700"
                    >
                      {d}
                    </span>
                  ))}
                </div>
              </div>

              {/* Footer */}
              <div className="pt-3 border-t border-[#E5EAF0] flex items-center justify-end gap-2.5">
                <button
                  type="button"
                  onClick={() => setIsDeptModalOpen(false)}
                  className="px-4 py-2 text-xs font-semibold text-[#64748B] bg-white hover:bg-slate-100 border border-[#E5EAF0] rounded-lg transition-colors cursor-pointer"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="px-5 py-2 text-xs font-bold text-white bg-[#1769E8] hover:bg-[#1257C7] rounded-lg transition-colors flex items-center gap-1.5 shadow-xs cursor-pointer"
                >
                  <Save className="w-3.5 h-3.5" />
                  <span>Save Department</span>
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
