"use client";

import React, { useState } from "react";
import Link from "next/link";
import {
  Search,
  RotateCcw,
  Plus,
  Eye,
  Edit2,
  Trash2,
  ChevronLeft,
  ChevronRight,
  FileSpreadsheet,
  FileText,
  UserCheck,
  Sparkles,
  BookOpen,
  Clock,
  CheckCircle2,
  AlertTriangle,
  X,
  Sliders,
} from "lucide-react";
import { toast } from "sonner";

interface FacultyWorkload {
  id: string;
  employeeId: string;
  name: string;
  designation: string;
  department: string;
  theoryHours: number;
  practicalHours: number;
  totalWeeklyHours: number;
  maxWeeklyHours: number;
  status: "Optimal" | "Heavy" | "Light";
}

const initialWorkloads: FacultyWorkload[] = [
  {
    id: "fw-1",
    employeeId: "EMP-041",
    name: "Chef Rajesh Sharma",
    designation: "Senior Lecturer & HOD Culinary",
    department: "Food Production",
    theoryHours: 2.0,
    practicalHours: 16.0,
    totalWeeklyHours: 18.0,
    maxWeeklyHours: 18.0,
    status: "Optimal",
  },
  {
    id: "fw-2",
    employeeId: "EMP-088",
    name: "Chef Amit Roy",
    designation: "Lecturer (Culinary Arts)",
    department: "Food Production",
    theoryHours: 2.0,
    practicalHours: 12.0,
    totalWeeklyHours: 14.0,
    maxWeeklyHours: 18.0,
    status: "Light",
  },
  {
    id: "fw-3",
    employeeId: "EMP-056",
    name: "Prof. Ananya Sen",
    designation: "Assistant Professor & In-Charge F&B",
    department: "F&B Service",
    theoryHours: 4.0,
    practicalHours: 8.0,
    totalWeeklyHours: 12.0,
    maxWeeklyHours: 16.0,
    status: "Light",
  },
  {
    id: "fw-4",
    employeeId: "EMP-092",
    name: "Chef Vikram Singh",
    designation: "Master Baker & Lecturer",
    department: "Food Production",
    theoryHours: 4.0,
    practicalHours: 18.0,
    totalWeeklyHours: 22.0,
    maxWeeklyHours: 18.0,
    status: "Heavy",
  },
  {
    id: "fw-5",
    employeeId: "EMP-034",
    name: "Prof. Priya Nair",
    designation: "Senior Lecturer",
    department: "Front Office",
    theoryHours: 6.0,
    practicalHours: 6.0,
    totalWeeklyHours: 12.0,
    maxWeeklyHours: 14.0,
    status: "Optimal",
  },
  {
    id: "fw-6",
    employeeId: "EMP-071",
    name: "Ms. Moumita Bose",
    designation: "Assistant Lecturer",
    department: "Housekeeping",
    theoryHours: 4.0,
    practicalHours: 6.0,
    totalWeeklyHours: 10.0,
    maxWeeklyHours: 16.0,
    status: "Light",
  },
];

export default function FacultyWorkloadPage() {
  const [workloads, setWorkloads] = useState<FacultyWorkload[]>(initialWorkloads);
  const [selectedDept, setSelectedDept] = useState("All Departments");
  const [selectedStatus, setSelectedStatus] = useState("All Status");
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedRows, setSelectedRows] = useState<string[]>([]);
  const [pageSize, setPageSize] = useState("10");

  // Modal State
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [viewingWorkload, setViewingWorkload] = useState<FacultyWorkload | null>(null);
  const [editingId, setEditingId] = useState<string | null>(null);

  const [formData, setFormData] = useState({
    employeeId: "EMP-041",
    name: "Chef Rajesh Sharma",
    designation: "Senior Lecturer & HOD Culinary",
    department: "Food Production",
    theoryHours: 2.0,
    practicalHours: 16.0,
    maxWeeklyHours: 18.0,
  });

  const filteredWorkloads = workloads.filter((w) => {
    const matchesDept =
      selectedDept === "All Departments" || w.department === selectedDept;
    const matchesStatus =
      selectedStatus === "All Status" || w.status === selectedStatus;
    const matchesSearch =
      searchQuery === "" ||
      w.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
      w.employeeId.toLowerCase().includes(searchQuery.toLowerCase()) ||
      w.department.toLowerCase().includes(searchQuery.toLowerCase()) ||
      w.designation.toLowerCase().includes(searchQuery.toLowerCase());
    return matchesDept && matchesStatus && matchesSearch;
  });

  const handleSelectAll = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.checked) {
      setSelectedRows(filteredWorkloads.map((w) => w.id));
    } else {
      setSelectedRows([]);
    }
  };

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

  const handleResetFilters = () => {
    setSelectedDept("All Departments");
    setSelectedStatus("All Status");
    setSearchQuery("");
    toast.info("Filters reset to default");
  };

  const calculateStatus = (total: number, max: number): "Optimal" | "Heavy" | "Light" => {
    if (total > max) return "Heavy";
    if (total >= max - 4) return "Optimal";
    return "Light";
  };

  const handleOpenAddModal = () => {
    setEditingId(null);
    setFormData({
      employeeId: "EMP-099",
      name: "",
      designation: "Lecturer",
      department: "Food Production",
      theoryHours: 4.0,
      practicalHours: 10.0,
      maxWeeklyHours: 16.0,
    });
    setIsModalOpen(true);
  };

  const handleEdit = (w: FacultyWorkload) => {
    setEditingId(w.id);
    setFormData({
      employeeId: w.employeeId,
      name: w.name,
      designation: w.designation,
      department: w.department,
      theoryHours: w.theoryHours,
      practicalHours: w.practicalHours,
      maxWeeklyHours: w.maxWeeklyHours,
    });
    setIsModalOpen(true);
  };

  const handleSubmitForm = (e: React.FormEvent) => {
    e.preventDefault();
    if (!formData.name) {
      toast.error("Please enter a faculty member name");
      return;
    }

    const totalHours = Number(formData.theoryHours) + Number(formData.practicalHours);
    const maxHours = Number(formData.maxWeeklyHours);
    const calculatedStatus = calculateStatus(totalHours, maxHours);

    if (editingId) {
      setWorkloads((prev) =>
        prev.map((w) =>
          w.id === editingId
            ? {
                ...w,
                name: formData.name,
                employeeId: formData.employeeId,
                designation: formData.designation,
                department: formData.department,
                theoryHours: Number(formData.theoryHours),
                practicalHours: Number(formData.practicalHours),
                totalWeeklyHours: totalHours,
                maxWeeklyHours: maxHours,
                status: calculatedStatus,
              }
            : w
        )
      );
      toast.success("Faculty workload quota updated");
    } else {
      const newWorkload: FacultyWorkload = {
        id: `fw-${Date.now()}`,
        employeeId: formData.employeeId,
        name: formData.name,
        designation: formData.designation,
        department: formData.department,
        theoryHours: Number(formData.theoryHours),
        practicalHours: Number(formData.practicalHours),
        totalWeeklyHours: totalHours,
        maxWeeklyHours: maxHours,
        status: calculatedStatus,
      };
      setWorkloads((prev) => [newWorkload, ...prev]);
      toast.success("New faculty workload allocation created");
    }

    setIsModalOpen(false);
  };

  const getStatusBadge = (status: "Optimal" | "Heavy" | "Light") => {
    switch (status) {
      case "Optimal":
        return "bg-[#DCFCE7] text-[#15803D] border-[#BBF7D0]";
      case "Heavy":
        return "bg-[#FEE2E2] text-[#DC2626] border-[#FECACA]";
      case "Light":
        return "bg-[#E0F2FE] text-[#0369A1] border-[#BAE6FD]";
    }
  };

  return (
    <div className="space-y-6 pb-12 font-sans bg-[#F8FAFC] min-h-screen">
      {/* 1. Header Bar */}
      <div>
        <div className="flex items-center gap-2 text-xs text-[#64748B] mb-2 font-medium">
          <Link href="/admin/dashboard" className="hover:text-[#1769E8] transition-colors">
            Home
          </Link>
          <span>&gt;</span>
          <Link href="/admin/people/faculty" className="hover:text-[#1769E8] transition-colors">
            Faculty Management
          </Link>
          <span>&gt;</span>
          <span className="text-[#071A4D] font-semibold">Faculty Workload</span>
        </div>

        <div className="flex flex-col md:flex-row md:items-center justify-between gap-4">
          <div>
            <h1 className="text-3xl font-bold font-heading text-[#071A4D] tracking-tight">
              Faculty Workload Distribution
            </h1>
            <p className="text-[15px] text-[#64748B] mt-1 font-normal">
              Monitor weekly theory lectures, culinary laboratory contact hours, and institutional workload compliance.
            </p>
          </div>

          <div className="flex items-center gap-3">
            <button
              onClick={() => toast.success("Exporting Workload Roster to Excel...")}
              className="px-4 py-2 bg-white border border-[#E2E8F0] rounded-lg text-sm font-medium text-[#334155] hover:bg-slate-50 transition-colors flex items-center gap-2 shadow-xs cursor-pointer"
            >
              <FileSpreadsheet className="w-4 h-4 text-emerald-600" />
              <span>Export</span>
            </button>
            <button
              onClick={() => toast.info("NCHMCT workload policy standards report...")}
              className="px-4 py-2 bg-white border border-[#E2E8F0] rounded-lg text-sm font-medium text-[#334155] hover:bg-slate-50 transition-colors flex items-center gap-2 shadow-xs cursor-pointer"
            >
              <FileText className="w-4 h-4 text-purple-600" />
              <span>Policy Standards</span>
            </button>
            <button
              onClick={handleOpenAddModal}
              className="px-5 py-2.5 bg-[#1769E8] hover:bg-[#1255be] text-white rounded-lg text-sm font-semibold transition-colors flex items-center gap-2 shadow-sm cursor-pointer"
            >
              <Plus className="w-4 h-4" />
              <span>+ Assign Workload</span>
            </button>
          </div>
        </div>
      </div>

      {/* 2. Filter Bar */}
      <div className="bg-white rounded-xl border border-[#E5EAF0] shadow-xs p-4">
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-12 gap-3.5 items-end">
          <div className="lg:col-span-3">
            <label className="block text-[11px] font-semibold text-[#64748B] uppercase tracking-wider mb-1.5">
              Department
            </label>
            <select
              value={selectedDept}
              onChange={(e) => setSelectedDept(e.target.value)}
              className="w-full bg-white border border-[#E2E8F0] text-sm text-[#0F172A] rounded-lg px-3 py-2 font-medium focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all cursor-pointer"
            >
              <option>All Departments</option>
              <option>Food Production</option>
              <option>F&B Service</option>
              <option>Front Office</option>
              <option>Housekeeping</option>
            </select>
          </div>

          <div className="lg:col-span-3">
            <label className="block text-[11px] font-semibold text-[#64748B] uppercase tracking-wider mb-1.5">
              Workload Status
            </label>
            <select
              value={selectedStatus}
              onChange={(e) => setSelectedStatus(e.target.value)}
              className="w-full bg-white border border-[#E2E8F0] text-sm text-[#0F172A] rounded-lg px-3 py-2 font-medium focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all cursor-pointer"
            >
              <option>All Status</option>
              <option value="Optimal">Optimal (Compliant)</option>
              <option value="Heavy">Heavy (Overload)</option>
              <option value="Light">Light (Underload)</option>
            </select>
          </div>

          <div className="lg:col-span-4">
            <label className="block text-[11px] font-semibold text-[#64748B] uppercase tracking-wider mb-1.5">
              Search
            </label>
            <div className="relative">
              <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-[#94A3B8]" />
              <input
                type="text"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder="Search faculty name, ID, or department..."
                className="w-full pl-9 pr-3 py-2 bg-white border border-[#E2E8F0] text-sm text-[#0F172A] placeholder:text-[#94A3B8] rounded-lg focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all"
              />
            </div>
          </div>

          <div className="lg:col-span-2 flex items-center gap-2">
            <button
              onClick={() => toast.success(`Found ${filteredWorkloads.length} workload records`)}
              className="flex-1 bg-[#1769E8] hover:bg-[#1255be] text-white py-2 rounded-lg text-sm font-semibold transition-colors flex items-center justify-center gap-1.5 shadow-xs cursor-pointer"
            >
              <Search className="w-4 h-4" />
              <span>Search</span>
            </button>
            <button
              onClick={handleResetFilters}
              className="border border-[#E2E8F0] hover:bg-slate-50 text-[#64748B] p-2 rounded-lg text-sm font-medium transition-colors flex items-center justify-center cursor-pointer"
              title="Reset Filters"
            >
              <RotateCcw className="w-4 h-4" />
            </button>
          </div>
        </div>
      </div>

      {/* 3. Full Width Table Card */}
      <div className="bg-white rounded-xl border border-[#E5EAF0] shadow-xs overflow-hidden">
        <div className="p-4 border-b border-[#E5EAF0] flex items-center justify-between">
          <div className="flex items-center gap-2.5">
            <Clock className="w-5 h-5 text-[#1769E8]" />
            <h2 className="font-heading font-bold text-lg text-[#071A4D]">
              Workload Allocation Roster ({filteredWorkloads.length})
            </h2>
          </div>
          <div className="flex items-center gap-2">
            <select
              value={pageSize}
              onChange={(e) => setPageSize(e.target.value)}
              className="text-xs bg-white border border-[#E2E8F0] rounded-lg px-2.5 py-1.5 font-medium text-[#475569] outline-none cursor-pointer"
            >
              <option value="10">10 per page</option>
              <option value="25">25 per page</option>
            </select>
          </div>
        </div>

        <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] font-semibold">
                <th className="py-3 px-3.5 w-10 text-center">
                  <input
                    type="checkbox"
                    checked={
                      selectedRows.length === filteredWorkloads.length &&
                      filteredWorkloads.length > 0
                    }
                    onChange={handleSelectAll}
                    className="rounded border-[#CBD5E1] text-[#1769E8] focus:ring-0 cursor-pointer"
                  />
                </th>
                <th className="py-3 px-2 w-8 text-center text-[#64748B]">#</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D]">Faculty Member</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D]">Department</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Theory Hours</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Practical Hours</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Total Load</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Threshold</th>
                <th className="py-3 px-3.5 font-bold text-[#071A4D] text-center">Compliance</th>
                <th className="py-3 px-4 font-bold text-[#071A4D] text-right">Actions</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[#E5EAF0]">
              {filteredWorkloads.length === 0 ? (
                <tr>
                  <td colSpan={10} className="py-12 text-center text-slate-400">
                    No workload allocations match the search filters.
                  </td>
                </tr>
              ) : (
                filteredWorkloads.map((w, idx) => (
                  <tr
                    key={w.id}
                    className={`hover:bg-[#F8FAFC] transition-colors ${
                      selectedRows.includes(w.id) ? "bg-[#EFF6FF]/40" : ""
                    }`}
                  >
                    <td className="py-3.5 px-3.5 text-center">
                      <input
                        type="checkbox"
                        checked={selectedRows.includes(w.id)}
                        onChange={() => handleRowSelect(w.id)}
                        className="rounded border-[#CBD5E1] text-[#1769E8] focus:ring-0 cursor-pointer"
                      />
                    </td>
                    <td className="py-3.5 px-2 text-center text-[#94A3B8] font-medium">
                      {idx + 1}
                    </td>
                    <td className="py-3.5 px-3.5">
                      <div className="flex items-center gap-2">
                        <span className="font-mono font-bold text-[10px] bg-[#F1F6FC] text-[#1769E8] px-1.5 py-0.5 rounded border border-[#D0E2FF]">
                          {w.employeeId}
                        </span>
                        <span className="font-bold text-[#071A4D] text-sm">{w.name}</span>
                      </div>
                      <div className="text-[11px] text-[#64748B] mt-0.5">{w.designation}</div>
                    </td>
                    <td className="py-3.5 px-3.5">
                      <span className="font-semibold text-[#334155]">{w.department}</span>
                    </td>
                    <td className="py-3.5 px-3.5 text-center font-mono font-bold text-[#334155]">
                      {w.theoryHours}h / wk
                    </td>
                    <td className="py-3.5 px-3.5 text-center font-mono font-bold text-[#334155]">
                      {w.practicalHours}h / wk
                    </td>
                    <td className="py-3.5 px-3.5 text-center">
                      <span className="font-mono font-bold text-sm text-[#1769E8]">
                        {w.totalWeeklyHours}h
                      </span>
                    </td>
                    <td className="py-3.5 px-3.5 text-center font-mono text-xs text-[#64748B]">
                      Max {w.maxWeeklyHours}h
                    </td>
                    <td className="py-3.5 px-3.5 text-center">
                      <span
                        className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-[11px] font-bold border ${getStatusBadge(
                          w.status
                        )}`}
                      >
                        {w.status}
                      </span>
                    </td>
                    <td className="py-3.5 px-4 text-right">
                      <div className="flex items-center justify-end gap-1.5">
                        <button
                          onClick={() => setViewingWorkload(w)}
                          className="p-1.5 text-[#64748B] hover:text-[#1769E8] hover:bg-[#EFF6FF] rounded-md transition-colors cursor-pointer"
                          title="View Breakdown"
                        >
                          <Eye className="w-3.5 h-3.5" />
                        </button>
                        <button
                          onClick={() => handleEdit(w)}
                          className="p-1.5 text-[#64748B] hover:text-[#1769E8] hover:bg-[#EFF6FF] rounded-md transition-colors cursor-pointer"
                          title="Adjust Workload"
                        >
                          <Edit2 className="w-3.5 h-3.5" />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        <div className="p-4 border-t border-[#E5EAF0] flex flex-col sm:flex-row items-center justify-between gap-3 text-xs text-[#64748B]">
          <div>
            Showing 1 to {filteredWorkloads.length} of {workloads.length} faculty workload quotas
          </div>
          <div className="flex items-center gap-1">
            <button className="p-1.5 border border-[#E2E8F0] rounded-md hover:bg-slate-50 transition-colors cursor-pointer">
              <ChevronLeft className="w-3.5 h-3.5" />
            </button>
            <button className="px-3 py-1 bg-[#1769E8] text-white font-bold rounded-md text-xs">
              1
            </button>
            <button className="p-1.5 border border-[#E2E8F0] rounded-md hover:bg-slate-50 transition-colors cursor-pointer">
              <ChevronRight className="w-3.5 h-3.5" />
            </button>
          </div>
        </div>
      </div>

      {/* 4. MODAL: Assign / Adjust Workload */}
      {isModalOpen && (
        <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="bg-white rounded-2xl border border-[#E5EAF0] shadow-xl max-w-lg w-full overflow-hidden">
            <div className="p-4 border-b border-[#E5EAF0] flex items-center justify-between bg-[#F8FAFC]">
              <div className="flex items-center gap-2">
                <Sliders className="w-5 h-5 text-[#1769E8]" />
                <h3 className="font-heading font-bold text-base text-[#071A4D]">
                  {editingId ? "Adjust Workload Quota" : "Assign Faculty Workload"}
                </h3>
              </div>
              <button
                onClick={() => setIsModalOpen(false)}
                className="p-1 text-[#64748B] hover:text-[#071A4D] rounded-md transition-colors cursor-pointer"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <form onSubmit={handleSubmitForm} className="p-5 space-y-4 text-xs">
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="block font-semibold text-[#334155] mb-1">
                    Employee ID <span className="text-rose-500">*</span>
                  </label>
                  <input
                    type="text"
                    required
                    value={formData.employeeId}
                    onChange={(e) => setFormData({ ...formData, employeeId: e.target.value })}
                    className="w-full px-3 py-2 border border-[#E2E8F0] rounded-lg text-sm text-[#0F172A] uppercase font-mono focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all"
                  />
                </div>

                <div>
                  <label className="block font-semibold text-[#334155] mb-1">
                    Department
                  </label>
                  <select
                    value={formData.department}
                    onChange={(e) => setFormData({ ...formData, department: e.target.value })}
                    className="w-full px-3 py-2 border border-[#E2E8F0] rounded-lg text-sm text-[#0F172A] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all bg-white cursor-pointer"
                  >
                    <option>Food Production</option>
                    <option>F&B Service</option>
                    <option>Front Office</option>
                    <option>Housekeeping</option>
                  </select>
                </div>
              </div>

              <div>
                <label className="block font-semibold text-[#334155] mb-1">
                  Faculty Name <span className="text-rose-500">*</span>
                </label>
                <input
                  type="text"
                  required
                  value={formData.name}
                  onChange={(e) => setFormData({ ...formData, name: e.target.value })}
                  placeholder="e.g. Chef Rajesh Sharma"
                  className="w-full px-3 py-2 border border-[#E2E8F0] rounded-lg text-sm text-[#0F172A] placeholder:text-[#94A3B8] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all"
                />
              </div>

              <div>
                <label className="block font-semibold text-[#334155] mb-1">
                  Academic Designation
                </label>
                <select
                  value={formData.designation}
                  onChange={(e) => setFormData({ ...formData, designation: e.target.value })}
                  className="w-full px-3 py-2 border border-[#E2E8F0] rounded-lg text-sm text-[#0F172A] focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all bg-white cursor-pointer"
                >
                  <option>Senior Lecturer &amp; HOD Culinary</option>
                  <option>Assistant Professor &amp; In-Charge F&amp;B</option>
                  <option>Senior Lecturer</option>
                  <option>Lecturer (Culinary Arts)</option>
                  <option>Assistant Lecturer</option>
                </select>
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-3 gap-3">
                <div>
                  <label className="block font-semibold text-[#334155] mb-1">
                    Theory (Hrs/Wk)
                  </label>
                  <input
                    type="number"
                    min="0"
                    max="20"
                    value={formData.theoryHours}
                    onChange={(e) =>
                      setFormData({ ...formData, theoryHours: parseFloat(e.target.value) || 0 })
                    }
                    className="w-full px-3 py-2 border border-[#E2E8F0] rounded-lg text-sm text-[#0F172A] font-mono focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all"
                  />
                </div>

                <div>
                  <label className="block font-semibold text-[#334155] mb-1">
                    Practical (Hrs/Wk)
                  </label>
                  <input
                    type="number"
                    min="0"
                    max="30"
                    value={formData.practicalHours}
                    onChange={(e) =>
                      setFormData({
                        ...formData,
                        practicalHours: parseFloat(e.target.value) || 0,
                      })
                    }
                    className="w-full px-3 py-2 border border-[#E2E8F0] rounded-lg text-sm text-[#0F172A] font-mono focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all"
                  />
                </div>

                <div>
                  <label className="block font-semibold text-[#334155] mb-1">
                    Max Quota
                  </label>
                  <input
                    type="number"
                    min="10"
                    max="30"
                    value={formData.maxWeeklyHours}
                    onChange={(e) =>
                      setFormData({
                        ...formData,
                        maxWeeklyHours: parseFloat(e.target.value) || 0,
                      })
                    }
                    className="w-full px-3 py-2 border border-[#E2E8F0] rounded-lg text-sm text-[#0F172A] font-mono focus:ring-2 focus:ring-[#1769E8]/20 focus:border-[#1769E8] outline-none transition-all"
                  />
                </div>
              </div>

              {/* Calculated Summary Callout */}
              <div className="p-3 bg-[#F1F6FC] rounded-lg border border-[#D0E2FF] flex items-center justify-between text-xs">
                <div>
                  <span className="text-[#64748B]">Total Weekly Contact Load:</span>
                  <div className="font-bold text-sm text-[#071A4D]">
                    {Number(formData.theoryHours) + Number(formData.practicalHours)} Hours / Week
                  </div>
                </div>
                <div>
                  <span
                    className={`inline-block px-2.5 py-1 rounded-full text-xs font-bold border ${getStatusBadge(
                      calculateStatus(
                        Number(formData.theoryHours) + Number(formData.practicalHours),
                        Number(formData.maxWeeklyHours)
                      )
                    )}`}
                  >
                    {calculateStatus(
                      Number(formData.theoryHours) + Number(formData.practicalHours),
                      Number(formData.maxWeeklyHours)
                    )}
                  </span>
                </div>
              </div>

              <div className="flex items-center gap-2 pt-3 border-t border-[#E5EAF0]">
                <button
                  type="button"
                  onClick={() => setIsModalOpen(false)}
                  className="flex-1 py-2 px-3 border border-[#E2E8F0] text-[#64748B] hover:bg-slate-50 rounded-lg text-xs font-semibold transition-colors cursor-pointer"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="flex-1 py-2 px-3 bg-[#1769E8] hover:bg-[#1255be] text-white rounded-lg text-xs font-semibold transition-colors flex items-center justify-center gap-1.5 shadow-xs cursor-pointer"
                >
                  <CheckCircle2 className="w-3.5 h-3.5" />
                  <span>{editingId ? "Update Quota" : "Save Allocation"}</span>
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* 5. MODAL: Workload Breakdown Dossier View */}
      {viewingWorkload && (
        <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="bg-white rounded-2xl border border-[#E5EAF0] shadow-xl max-w-md w-full overflow-hidden">
            <div className="p-4 border-b border-[#E5EAF0] flex items-center justify-between bg-[#F8FAFC]">
              <div className="flex items-center gap-2">
                <Clock className="w-5 h-5 text-[#1769E8]" />
                <h3 className="font-heading font-bold text-base text-[#071A4D]">
                  Workload Breakdown
                </h3>
              </div>
              <button
                onClick={() => setViewingWorkload(null)}
                className="p-1 text-[#64748B] hover:text-[#071A4D] rounded-md transition-colors cursor-pointer"
              >
                <X className="w-5 h-5" />
              </button>
            </div>

            <div className="p-5 space-y-4 text-xs">
              <div className="flex items-center justify-between pb-3 border-b border-[#E5EAF0]">
                <div>
                  <span className="font-mono text-xs font-bold px-2 py-0.5 rounded bg-blue-50 text-[#1769E8] border border-blue-200">
                    {viewingWorkload.employeeId}
                  </span>
                  <h4 className="font-heading font-bold text-base text-[#071A4D] mt-1.5">
                    {viewingWorkload.name}
                  </h4>
                  <p className="text-[11px] text-[#64748B]">{viewingWorkload.designation}</p>
                </div>
                <span
                  className={`px-2.5 py-1 rounded-full text-xs font-bold border ${getStatusBadge(
                    viewingWorkload.status
                  )}`}
                >
                  {viewingWorkload.status}
                </span>
              </div>

              <div className="space-y-2 text-[#475569]">
                <div className="flex items-center justify-between p-2.5 bg-[#F8FAFC] rounded-lg border border-[#E5EAF0]">
                  <span className="font-medium">Department</span>
                  <span className="font-bold text-[#071A4D]">{viewingWorkload.department}</span>
                </div>
                <div className="flex items-center justify-between p-2.5 bg-[#F8FAFC] rounded-lg border border-[#E5EAF0]">
                  <span className="font-medium">Theory Lecture Hours</span>
                  <span className="font-mono font-bold text-[#071A4D]">
                    {viewingWorkload.theoryHours}h / week
                  </span>
                </div>
                <div className="flex items-center justify-between p-2.5 bg-[#F8FAFC] rounded-lg border border-[#E5EAF0]">
                  <span className="font-medium">Practical &amp; Lab Sessions</span>
                  <span className="font-mono font-bold text-[#071A4D]">
                    {viewingWorkload.practicalHours}h / week
                  </span>
                </div>
                <div className="flex items-center justify-between p-2.5 bg-[#F8FAFC] rounded-lg border border-[#E5EAF0]">
                  <span className="font-medium">Total Weekly Contact Load</span>
                  <span className="font-mono font-bold text-[#1769E8] text-sm">
                    {viewingWorkload.totalWeeklyHours} Hours
                  </span>
                </div>
                <div className="flex items-center justify-between p-2.5 bg-[#F8FAFC] rounded-lg border border-[#E5EAF0]">
                  <span className="font-medium">Institutional Threshold Ceiling</span>
                  <span className="font-mono font-bold text-[#64748B]">
                    Max {viewingWorkload.maxWeeklyHours} Hours
                  </span>
                </div>
              </div>

              <div className="flex items-center justify-end gap-2 pt-3 border-t border-[#E5EAF0]">
                <button
                  type="button"
                  onClick={() => {
                    const toEdit = viewingWorkload;
                    setViewingWorkload(null);
                    handleEdit(toEdit);
                  }}
                  className="py-2 px-3 border border-[#E2E8F0] hover:bg-slate-50 text-[#334155] rounded-lg text-xs font-semibold transition-colors cursor-pointer"
                >
                  Edit Quota
                </button>
                <button
                  type="button"
                  onClick={() => setViewingWorkload(null)}
                  className="py-2 px-4 bg-[#1769E8] hover:bg-[#1255be] text-white rounded-lg text-xs font-semibold transition-colors cursor-pointer"
                >
                  Close
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
