"use client";

import React, { useState } from "react";
import Link from "next/link";
import {
  Users,
  Plus,
  Search,
  Filter,
  CheckCircle2,
  ChevronRight,
  UtensilsCrossed,
  DoorOpen,
  UserCheck,
  X,
  Layers,
} from "lucide-react";
import { toast } from "sonner";

interface GroupItem {
  id: string;
  name: string;
  type: "KITCHEN_PRACTICAL" | "THEORY_SECTION" | "BAKERY_STUDIO";
  semester: number;
  enrolled: number;
  capacity: number;
  facility: string;
  leadFaculty: string;
}

export default function DeptAdminGroupsPage() {
  const [groups, setGroups] = useState<GroupItem[]>([
    {
      id: "grp_1",
      name: "Kitchen Batch K1 (BTK)",
      type: "KITCHEN_PRACTICAL",
      semester: 1,
      enrolled: 34,
      capacity: 35,
      facility: "Basic Training Kitchen (BTK)",
      leadFaculty: "Chef Rajesh Sharma",
    },
    {
      id: "grp_2",
      name: "Kitchen Batch K2 (BTK)",
      type: "KITCHEN_PRACTICAL",
      semester: 1,
      enrolled: 34,
      capacity: 35,
      facility: "Basic Training Kitchen (BTK)",
      leadFaculty: "Chef Anirban Roy",
    },
    {
      id: "grp_3",
      name: "Theory Section A",
      type: "THEORY_SECTION",
      semester: 1,
      enrolled: 68,
      capacity: 70,
      facility: "Lecture Hall 204",
      leadFaculty: "Chef Anirban Roy",
    },
    {
      id: "grp_4",
      name: "Quantity Food Batch Q1",
      type: "KITCHEN_PRACTICAL",
      semester: 3,
      enrolled: 31,
      capacity: 32,
      facility: "Quantity Food Kitchen (QFK)",
      leadFaculty: "Chef Amit Sen",
    },
    {
      id: "grp_5",
      name: "Quantity Food Batch Q2",
      type: "KITCHEN_PRACTICAL",
      semester: 3,
      enrolled: 31,
      capacity: 32,
      facility: "Quantity Food Kitchen (QFK)",
      leadFaculty: "Chef Meenakshi Iyer",
    },
    {
      id: "grp_6",
      name: "Bakery Studio Batch B1",
      type: "BAKERY_STUDIO",
      semester: 1,
      enrolled: 24,
      capacity: 25,
      facility: "Bakery & Confectionery Lab",
      leadFaculty: "Chef Meenakshi Iyer",
    },
    {
      id: "grp_7",
      name: "Advanced Culinary Batch A1",
      type: "KITCHEN_PRACTICAL",
      semester: 5,
      enrolled: 30,
      capacity: 30,
      facility: "Advanced Training Kitchen (ATK)",
      leadFaculty: "Chef David Rozario",
    },
  ]);

  const [search, setSearch] = useState("");
  const [semFilter, setSemFilter] = useState<number | "ALL">("ALL");
  const [isModalOpen, setIsModalOpen] = useState(false);

  const [formName, setFormName] = useState("");
  const [formType, setFormType] = useState<"KITCHEN_PRACTICAL" | "THEORY_SECTION" | "BAKERY_STUDIO">("KITCHEN_PRACTICAL");
  const [formSem, setFormSem] = useState(1);
  const [formCapacity, setFormCapacity] = useState(35);
  const [formFacility, setFormFacility] = useState("Basic Training Kitchen (BTK)");
  const [formFaculty, setFormFaculty] = useState("Chef Rajesh Sharma");

  const filtered = groups.filter((g) => {
    const matchesSem = semFilter === "ALL" || g.semester === semFilter;
    const matchesSearch =
      g.name.toLowerCase().includes(search.toLowerCase()) ||
      g.facility.toLowerCase().includes(search.toLowerCase());
    return matchesSem && matchesSearch;
  });

  const handleCreateGroup = (e: React.FormEvent) => {
    e.preventDefault();
    if (!formName.trim()) {
      toast.error("Please enter group name");
      return;
    }

    const newGroup: GroupItem = {
      id: `grp_${Date.now()}`,
      name: formName,
      type: formType,
      semester: Number(formSem),
      enrolled: 0,
      capacity: Number(formCapacity),
      facility: formFacility,
      leadFaculty: formFaculty,
    };

    setGroups([...groups, newGroup]);
    setIsModalOpen(false);
    setFormName("");
    toast.success(`Group created: ${newGroup.name}`);
  };

  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">Group Management</span>
          </div>
          <h1 className="text-xl sm:text-2xl font-black text-[#071A4D] tracking-tight">
            Group & Kitchen Batch Management
          </h1>
          <p className="text-xs text-slate-500 mt-0.5">
            Manage practical kitchen stations, bakery groups, and theory lecture sections
          </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>Create New Batch / Group</span>
        </button>
      </div>

      {/* Filter and Search */}
      <div className="flex flex-col sm:flex-row items-center justify-between gap-3 bg-white p-3.5 rounded-xl border border-slate-200 shadow-xs">
        <div className="relative w-full sm:w-72">
          <Search className="w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
          <input
            type="text"
            placeholder="Search group name or facility..."
            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 className="flex items-center gap-1.5 text-xs w-full sm:w-auto">
          <span className="font-semibold text-slate-500">Filter Semester:</span>
          {["ALL", 1, 3, 5].map((sem) => (
            <button
              key={String(sem)}
              onClick={() => setSemFilter(sem as any)}
              className={`px-3 py-1 rounded-lg font-bold text-xs transition-colors ${
                semFilter === sem
                  ? "bg-[#081A2E] text-white"
                  : "bg-slate-100 text-slate-600 hover:bg-slate-200"
              }`}
            >
              {sem === "ALL" ? "All" : `Sem ${sem}`}
            </button>
          ))}
        </div>
      </div>

      {/* Groups Grid */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-5">
        {filtered.map((g) => {
          const fillPercent = Math.round((g.enrolled / g.capacity) * 100);
          return (
            <div
              key={g.id}
              className="p-5 rounded-xl bg-white border border-slate-200 shadow-xs hover:shadow-md transition-all flex flex-col justify-between"
            >
              <div>
                <div className="flex items-start justify-between gap-2 mb-2">
                  <span
                    className={`text-[10px] font-bold px-2 py-0.5 rounded-full uppercase ${
                      g.type === "KITCHEN_PRACTICAL"
                        ? "bg-amber-100 text-amber-900 border border-amber-200"
                        : g.type === "BAKERY_STUDIO"
                        ? "bg-pink-100 text-pink-900 border border-pink-200"
                        : "bg-blue-100 text-blue-900 border border-blue-200"
                    }`}
                  >
                    {g.type.replace("_", " ")}
                  </span>
                  <span className="text-xs font-semibold text-slate-500">
                    Sem {g.semester}
                  </span>
                </div>

                <h3 className="text-base font-bold text-[#071A4D]">{g.name}</h3>

                <div className="space-y-2 py-3 border-y border-slate-100 text-xs mt-3">
                  <div className="flex items-center gap-2 text-slate-600">
                    <DoorOpen className="w-3.5 h-3.5 text-slate-400 shrink-0" />
                    <span className="truncate">{g.facility}</span>
                  </div>
                  <div className="flex items-center gap-2 text-slate-600">
                    <UserCheck className="w-3.5 h-3.5 text-[#C8A45D] shrink-0" />
                    <span>In-charge: <strong>{g.leadFaculty}</strong></span>
                  </div>
                </div>
              </div>

              <div className="pt-3 mt-3">
                <div className="flex items-center justify-between text-xs font-bold mb-1">
                  <span className="text-slate-600">Capacity Utilization</span>
                  <span className="text-[#071A4D]">{g.enrolled} / {g.capacity}</span>
                </div>
                <div className="w-full bg-slate-100 h-2 rounded-full overflow-hidden">
                  <div
                    className={`h-full rounded-full ${
                      fillPercent >= 95 ? "bg-amber-500" : "bg-[#081A2E]"
                    }`}
                    style={{ width: `${fillPercent}%` }}
                  />
                </div>
              </div>
            </div>
          );
        })}
      </div>

      {/* 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-md 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]">Create Practical Batch / Group</h3>
              <button onClick={() => setIsModalOpen(false)}>
                <X className="w-5 h-5 text-slate-400" />
              </button>
            </div>

            <form onSubmit={handleCreateGroup} className="space-y-4 pt-4 text-xs">
              <div>
                <label className="font-bold text-slate-800 block mb-1">Group / Batch Name *</label>
                <input
                  type="text"
                  placeholder="e.g. Kitchen Batch K3 (BTK)"
                  value={formName}
                  onChange={(e) => setFormName(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">Group Category</label>
                  <select
                    value={formType}
                    onChange={(e) => setFormType(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="KITCHEN_PRACTICAL">Kitchen Practical Batch</option>
                    <option value="BAKERY_STUDIO">Bakery Studio Batch</option>
                    <option value="THEORY_SECTION">Theory Section</option>
                  </select>
                </div>
                <div>
                  <label className="font-bold text-slate-800 block mb-1">Semester</label>
                  <select
                    value={formSem}
                    onChange={(e) => setFormSem(Number(e.target.value))}
                    className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:outline-hidden focus:border-[#C8A45D]"
                  >
                    {[1, 2, 3, 4, 5, 6].map((s) => (
                      <option key={s} value={s}>
                        Sem {s}
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              <div className="grid grid-cols-2 gap-3">
                <div>
                  <label className="font-bold text-slate-800 block mb-1">Max Student Capacity</label>
                  <input
                    type="number"
                    value={formCapacity}
                    onChange={(e) => setFormCapacity(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 Chef / Faculty</label>
                  <input
                    type="text"
                    value={formFaculty}
                    onChange={(e) => setFormFaculty(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>
                <label className="font-bold text-slate-800 block mb-1">Designated Kitchen / Lab</label>
                <input
                  type="text"
                  value={formFacility}
                  onChange={(e) => setFormFacility(e.target.value)}
                  className="w-full px-3 py-2 border border-slate-200 rounded-lg focus:outline-hidden focus:border-[#C8A45D]"
                />
              </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 Group
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
