"use client";

import React, { useState } from "react";
import Link from "next/link";
import {
  UserCheck,
  Plus,
  Search,
  Filter,
  CheckCircle2,
  ChevronRight,
  Clock,
  BookOpen,
  UtensilsCrossed,
  AlertTriangle,
  X,
  User,
  ShieldCheck,
} from "lucide-react";
import { toast } from "sonner";

interface FacultyAllocation {
  id: string;
  name: string;
  designation: string;
  empId: string;
  email: string;
  assignedSubjects: {
    code: string;
    name: string;
    type: "THEORY" | "PRACTICAL";
    hours: number;
    batch: string;
  }[];
  totalHours: number;
  maxHours: number;
  status: "NORMAL" | "NEAR_LIMIT" | "OVERLOADED";
}

export default function DeptAdminFacultyAllocationPage() {
  const [allocations, setAllocations] = useState<FacultyAllocation[]>([
    {
      id: "fac_1",
      name: "Chef Rajesh Sharma",
      designation: "Head of Department (Food Production)",
      empId: "EMP-FP-001",
      email: "rajesh.sharma@ihm.edu.in",
      assignedSubjects: [
        { code: "BHM311", name: "Advanced Food Production", type: "THEORY", hours: 2, batch: "Sem 5" },
        { code: "BHM111P", name: "Basic Culinary Lab", type: "PRACTICAL", hours: 6, batch: "Sem 1 (Batch K1)" },
        { code: "BHM311P", name: "International Culinary Arts", type: "PRACTICAL", hours: 6, batch: "Sem 5 (Batch A1)" },
      ],
      totalHours: 14,
      maxHours: 18,
      status: "NORMAL",
    },
    {
      id: "fac_2",
      name: "Chef Anirban Roy",
      designation: "Senior Lecturer",
      empId: "EMP-FP-002",
      email: "anirban.roy@ihm.edu.in",
      assignedSubjects: [
        { code: "BHM111", name: "Food Production Foundation", type: "THEORY", hours: 4, batch: "Sem 1 (Sec A & B)" },
        { code: "BHM111P", name: "Basic Culinary Lab", type: "PRACTICAL", hours: 12, batch: "Sem 1 (Batch K1 & K2)" },
      ],
      totalHours: 16,
      maxHours: 18,
      status: "NEAR_LIMIT",
    },
    {
      id: "fac_3",
      name: "Chef Amit Sen",
      designation: "Lecturer",
      empId: "EMP-FP-003",
      email: "amit.sen@ihm.edu.in",
      assignedSubjects: [
        { code: "BHM211", name: "Quantity Food Operations", type: "THEORY", hours: 3, batch: "Sem 3" },
        { code: "BHM211P", name: "Quantity Food Kitchen (QFK)", type: "PRACTICAL", hours: 12, batch: "Sem 3 (Batch Q1 & Q2)" },
      ],
      totalHours: 15,
      maxHours: 18,
      status: "NORMAL",
    },
    {
      id: "fac_4",
      name: "Chef Meenakshi Iyer",
      designation: "Lecturer (Bakery Specialist)",
      empId: "EMP-FP-004",
      email: "meenakshi.iyer@ihm.edu.in",
      assignedSubjects: [
        { code: "BHM114P", name: "Bakery Practical", type: "PRACTICAL", hours: 8, batch: "Sem 1 (Batch B1 & B2)" },
        { code: "CBC101P", name: "Advanced Pastry Studio", type: "PRACTICAL", hours: 8, batch: "Certificate Batch" },
      ],
      totalHours: 16,
      maxHours: 18,
      status: "NEAR_LIMIT",
    },
    {
      id: "fac_5",
      name: "Chef David Rozario",
      designation: "Assistant Lecturer (Larder)",
      empId: "EMP-FP-005",
      email: "david.rozario@ihm.edu.in",
      assignedSubjects: [
        { code: "BHM311P", name: "International Larder Practical", type: "PRACTICAL", hours: 12, batch: "Sem 5 (Batch A1 & A2)" },
      ],
      totalHours: 12,
      maxHours: 18,
      status: "NORMAL",
    },
  ]);

  const [search, setSearch] = useState("");
  const [isModalOpen, setIsModalOpen] = useState(false);

  const [selectedFacultyId, setSelectedFacultyId] = useState("fac_2");
  const [allocSubjectCode, setAllocSubjectCode] = useState("BHM111P");
  const [allocSubjectName, setAllocSubjectName] = useState("Basic Culinary Lab");
  const [allocType, setAllocType] = useState<"THEORY" | "PRACTICAL">("PRACTICAL");
  const [allocHours, setAllocHours] = useState(3);
  const [allocBatch, setAllocBatch] = useState("Sem 1 (Batch K2)");

  const filtered = allocations.filter(
    (a) =>
      a.name.toLowerCase().includes(search.toLowerCase()) ||
      a.empId.toLowerCase().includes(search.toLowerCase())
  );

  const handleAllocate = (e: React.FormEvent) => {
    e.preventDefault();
    setAllocations(
      allocations.map((fac) => {
        if (fac.id === selectedFacultyId) {
          const newHours = fac.totalHours + Number(allocHours);
          return {
            ...fac,
            totalHours: newHours,
            status: newHours > fac.maxHours ? "OVERLOADED" : newHours >= 16 ? "NEAR_LIMIT" : "NORMAL",
            assignedSubjects: [
              ...fac.assignedSubjects,
              {
                code: allocSubjectCode,
                name: allocSubjectName,
                type: allocType,
                hours: Number(allocHours),
                batch: allocBatch,
              },
            ],
          };
        }
        return fac;
      })
    );
    setIsModalOpen(false);
    toast.success("Faculty allocation saved successfully");
  };

  return (
    <div className="p-4 sm:p-6 lg:p-8 space-y-6 max-w-7xl mx-auto">
      {/* Header */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
        <div>
          <div className="flex items-center gap-2 text-xs font-semibold text-slate-500 mb-1">
            <Link href="/dept-admin/dashboard" className="hover:text-[#1769E8]">
              Dashboard
            </Link>
            <ChevronRight className="w-3.5 h-3.5" />
            <span className="text-[#071A4D] font-bold">Faculty Allocation</span>
          </div>
          <h1 className="text-xl sm:text-2xl font-black text-[#071A4D] tracking-tight">
            Faculty Teaching & Practical Allocation
          </h1>
          <p className="text-xs text-slate-500 mt-0.5">
            Assign department lecturers & chefs to theory subjects, kitchen practicals, and student batches
          </p>
        </div>

        <button
          onClick={() => setIsModalOpen(true)}
          className="inline-flex items-center gap-2 px-4 py-2.5 rounded-lg bg-[#C8A45D] hover:bg-[#B38F48] text-slate-950 font-bold text-xs shadow-sm transition-all"
        >
          <Plus className="w-4 h-4" />
          <span>Allocate Faculty to Class</span>
        </button>
      </div>

      {/* Summary KPI Strip */}
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        <div className="p-4 rounded-xl bg-white border border-slate-200 shadow-xs flex items-center justify-between">
          <div>
            <div className="text-xs text-slate-500">Total Department Faculty</div>
            <div className="text-xl font-bold text-[#071A4D]">{allocations.length} Active Chefs</div>
          </div>
          <div className="p-2.5 rounded-lg bg-blue-50 text-blue-700">
            <UserCheck className="w-5 h-5" />
          </div>
        </div>

        <div className="p-4 rounded-xl bg-white border border-slate-200 shadow-xs flex items-center justify-between">
          <div>
            <div className="text-xs text-slate-500">Average Weekly Load</div>
            <div className="text-xl font-bold text-[#071A4D]">14.6 hrs / week</div>
          </div>
          <div className="p-2.5 rounded-lg bg-amber-50 text-[#C8A45D]">
            <Clock className="w-5 h-5" />
          </div>
        </div>

        <div className="p-4 rounded-xl bg-white border border-slate-200 shadow-xs flex items-center justify-between">
          <div>
            <div className="text-xs text-slate-500">Institutional Ceiling</div>
            <div className="text-xl font-bold text-emerald-700">18 hrs / week max</div>
          </div>
          <div className="p-2.5 rounded-lg bg-emerald-50 text-emerald-700">
            <ShieldCheck className="w-5 h-5" />
          </div>
        </div>
      </div>

      {/* Search */}
      <div className="bg-white p-3.5 rounded-xl border border-slate-200 shadow-xs">
        <div className="relative max-w-sm">
          <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
          <input
            type="text"
            placeholder="Search faculty name or Employee ID..."
            value={search}
            onChange={(e) => setSearch(e.target.value)}
            className="w-full pl-9 pr-3 py-1.5 text-xs rounded-lg border border-slate-200 focus:outline-hidden focus:border-[#C8A45D]"
          />
        </div>
      </div>

      {/* Faculty Cards */}
      <div className="space-y-4">
        {filtered.map((fac) => {
          const loadPercent = Math.min(100, Math.round((fac.totalHours / fac.maxHours) * 100));
          return (
            <div
              key={fac.id}
              className="p-5 rounded-xl bg-white border border-slate-200 shadow-xs hover:shadow-md transition-all space-y-4"
            >
              <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3">
                <div className="flex items-center gap-3">
                  <div className="w-11 h-11 rounded-full bg-[#081A2E] text-[#C8A45D] font-bold text-sm flex items-center justify-center shrink-0 border-2 border-[#C8A45D]">
                    {fac.name.split(" ")[1]?.charAt(0) || "C"}
                  </div>
                  <div>
                    <div className="flex items-center gap-2">
                      <h3 className="text-base font-bold text-[#071A4D]">{fac.name}</h3>
                      <span className="text-[10px] font-mono bg-slate-100 text-slate-700 px-2 py-0.5 rounded-md">
                        {fac.empId}
                      </span>
                    </div>
                    <p className="text-xs text-slate-500">{fac.designation} • {fac.email}</p>
                  </div>
                </div>

                <div className="flex items-center gap-3">
                  <div className="text-right">
                    <div className="text-xs font-bold text-slate-800">
                      {fac.totalHours} / {fac.maxHours} Hours
                    </div>
                    <div className="text-[10px] text-slate-400">Weekly teaching load</div>
                  </div>

                  <span
                    className={`text-[10px] font-bold px-2.5 py-1 rounded-full uppercase ${
                      fac.status === "NORMAL"
                        ? "bg-emerald-100 text-emerald-800"
                        : fac.status === "NEAR_LIMIT"
                        ? "bg-amber-100 text-amber-800"
                        : "bg-rose-100 text-rose-800 animate-pulse"
                    }`}
                  >
                    {fac.status === "NORMAL"
                      ? "Optimal"
                      : fac.status === "NEAR_LIMIT"
                      ? "Near Ceiling"
                      : "Overloaded"}
                  </span>
                </div>
              </div>

              {/* Progress bar */}
              <div>
                <div className="w-full bg-slate-100 h-2 rounded-full overflow-hidden">
                  <div
                    className={`h-full rounded-full transition-all ${
                      loadPercent >= 90
                        ? "bg-amber-500"
                        : loadPercent > 100
                        ? "bg-rose-500"
                        : "bg-[#081A2E]"
                    }`}
                    style={{ width: `${loadPercent}%` }}
                  />
                </div>
              </div>

              {/* Assigned Subjects Badges */}
              <div>
                <span className="text-[10px] uppercase font-bold text-slate-400 block mb-2">
                  Assigned Subjects & Lab Batches
                </span>
                <div className="flex flex-wrap gap-2">
                  {fac.assignedSubjects.map((sub, i) => (
                    <div
                      key={i}
                      className="px-3 py-1.5 rounded-lg bg-slate-50 border border-slate-200 text-xs flex items-center gap-2"
                    >
                      <span className="font-mono font-bold text-[#071A4D]">{sub.code}</span>
                      <span className="text-slate-700">{sub.name}</span>
                      <span className="text-[10px] font-semibold text-[#785E2F] bg-amber-50 px-1.5 py-0.5 rounded-sm">
                        {sub.batch}
                      </span>
                      <span className="text-[10px] font-bold text-slate-500">{sub.hours}h</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* Allocation Modal */}
      {isModalOpen && (
        <div className="fixed inset-0 z-50 bg-slate-900/60 backdrop-blur-xs flex items-center justify-center p-4">
          <div className="bg-white rounded-2xl max-w-lg w-full p-6 shadow-2xl border border-slate-200">
            <div className="flex items-center justify-between pb-3 border-b border-slate-100">
              <h3 className="font-bold text-base text-[#071A4D]">Allocate Faculty to Class</h3>
              <button onClick={() => setIsModalOpen(false)}>
                <X className="w-5 h-5 text-slate-400" />
              </button>
            </div>

            <form onSubmit={handleAllocate} className="space-y-4 pt-4 text-xs">
              <div>
                <label className="font-bold text-slate-800 block mb-1">Select Faculty Member *</label>
                <select
                  value={selectedFacultyId}
                  onChange={(e) => setSelectedFacultyId(e.target.value)}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:outline-hidden focus:border-[#C8A45D]"
                >
                  {allocations.map((f) => (
                    <option key={f.id} value={f.id}>
                      {f.name} ({f.designation}) — Current: {f.totalHours}h
                    </option>
                  ))}
                </select>
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="font-bold text-slate-800 block mb-1">Subject Code *</label>
                  <input
                    type="text"
                    value={allocSubjectCode}
                    onChange={(e) => setAllocSubjectCode(e.target.value)}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:outline-hidden focus:border-[#C8A45D]"
                    required
                  />
                </div>
                <div>
                  <label className="font-bold text-slate-800 block mb-1">Class Type</label>
                  <select
                    value={allocType}
                    onChange={(e) => setAllocType(e.target.value as any)}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:outline-hidden focus:border-[#C8A45D]"
                  >
                    <option value="PRACTICAL">Kitchen Practical (Lab)</option>
                    <option value="THEORY">Theory Lecture</option>
                  </select>
                </div>
              </div>

              <div>
                <label className="font-bold text-slate-800 block mb-1">Subject Title</label>
                <input
                  type="text"
                  value={allocSubjectName}
                  onChange={(e) => setAllocSubjectName(e.target.value)}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:outline-hidden focus:border-[#C8A45D]"
                  required
                />
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="font-bold text-slate-800 block mb-1">Weekly Hours</label>
                  <input
                    type="number"
                    value={allocHours}
                    onChange={(e) => setAllocHours(Number(e.target.value))}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:outline-hidden focus:border-[#C8A45D]"
                  />
                </div>
                <div>
                  <label className="font-bold text-slate-800 block mb-1">Assigned Batch / Cohort</label>
                  <input
                    type="text"
                    value={allocBatch}
                    onChange={(e) => setAllocBatch(e.target.value)}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:outline-hidden focus:border-[#C8A45D]"
                  />
                </div>
              </div>

              <div className="pt-3 border-t border-slate-100 flex justify-end gap-2">
                <button
                  type="button"
                  onClick={() => setIsModalOpen(false)}
                  className="px-4 py-2 rounded-lg border border-slate-200 font-bold text-slate-600 hover:bg-slate-50"
                >
                  Cancel
                </button>
                <button
                  type="submit"
                  className="px-4 py-2 rounded-lg bg-[#C8A45D] text-slate-950 font-bold hover:bg-[#B38F48]"
                >
                  Save Allocation
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
