"use client";

import React, { useState } from "react";
import Link from "next/link";
import {
  CalendarHeart,
  Plus,
  Search,
  Filter,
  CheckCircle2,
  ChevronRight,
  Calendar,
  AlertCircle,
  X,
  Sparkles,
} from "lucide-react";
import { toast } from "sonner";

interface HolidayItem {
  id: string;
  name: string;
  date: string;
  day: string;
  category: "NATIONAL" | "REGIONAL" | "INSTITUTIONAL" | "DEPARTMENTAL";
  impactOnAttendance: string;
  daysCount: number;
}

export default function DeptAdminHolidaysPage() {
  const [holidays, setHolidays] = useState<HolidayItem[]>([
    {
      id: "hol_1",
      name: "Independence Day",
      date: "15 Aug 2024",
      day: "Thursday",
      category: "NATIONAL",
      impactOnAttendance: "Exempted from working days",
      daysCount: 1,
    },
    {
      id: "hol_2",
      name: "Gandhi Jayanti",
      date: "02 Oct 2024",
      day: "Wednesday",
      category: "NATIONAL",
      impactOnAttendance: "Exempted from working days",
      daysCount: 1,
    },
    {
      id: "hol_3",
      name: "Durga Puja & Dussehra Vacation",
      date: "09 Oct 2024 – 18 Oct 2024",
      day: "Wednesday – Friday",
      category: "REGIONAL",
      impactOnAttendance: "Exempted (10 days vacation)",
      daysCount: 10,
    },
    {
      id: "hol_4",
      name: "Diwali & Kali Puja",
      date: "31 Oct 2024 – 01 Nov 2024",
      day: "Thursday – Friday",
      category: "REGIONAL",
      impactOnAttendance: "Exempted from working days",
      daysCount: 2,
    },
    {
      id: "hol_5",
      name: "Culinary Exposition & Setup Holiday",
      date: "14 Nov 2024",
      day: "Thursday",
      category: "DEPARTMENTAL",
      impactOnAttendance: "Departmental Kitchens Suspended",
      daysCount: 1,
    },
    {
      id: "hol_6",
      name: "Winter Break & Christmas",
      date: "23 Dec 2024 – 03 Jan 2025",
      day: "Monday – Friday",
      category: "INSTITUTIONAL",
      impactOnAttendance: "Semester Recess (12 days)",
      daysCount: 12,
    },
  ]);

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

  const [formName, setFormName] = useState("");
  const [formDate, setFormDate] = useState("");
  const [formDay, setFormDay] = useState("Monday");
  const [formCategory, setFormCategory] = useState<HolidayItem["category"]>("DEPARTMENTAL");
  const [formDaysCount, setFormDaysCount] = useState(1);

  const filtered = holidays.filter((h) => {
    const matchesCat = categoryFilter === "ALL" || h.category === categoryFilter;
    const matchesSearch =
      h.name.toLowerCase().includes(search.toLowerCase()) ||
      h.date.toLowerCase().includes(search.toLowerCase());
    return matchesCat && matchesSearch;
  });

  const handleAddHoliday = (e: React.FormEvent) => {
    e.preventDefault();
    if (!formName.trim() || !formDate.trim()) {
      toast.error("Please fill holiday title and date");
      return;
    }

    const newHol: HolidayItem = {
      id: `hol_${Date.now()}`,
      name: formName,
      date: formDate,
      day: formDay,
      category: formCategory,
      impactOnAttendance: "Exempted from working days",
      daysCount: Number(formDaysCount),
    };

    setHolidays([...holidays, newHol]);
    setIsModalOpen(false);
    setFormName("");
    setFormDate("");
    toast.success(`Holiday declared: ${newHol.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">Holiday Calendar</span>
          </div>
          <h1 className="text-xl sm:text-2xl font-black text-[#071A4D] tracking-tight">
            Holiday Calendar & Attendance Exemptions
          </h1>
          <p className="text-xs text-slate-500 mt-0.5">
            Official gazetted holidays and institutional breaks exempted from attendance denominators
          </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>Declare Holiday</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 holiday name or date..."
            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 overflow-x-auto">
          <span className="font-semibold text-slate-500 shrink-0">Category:</span>
          {["ALL", "NATIONAL", "REGIONAL", "INSTITUTIONAL", "DEPARTMENTAL"].map((cat) => (
            <button
              key={cat}
              onClick={() => setCategoryFilter(cat)}
              className={`px-3 py-1 rounded-lg font-bold text-xs transition-colors whitespace-nowrap ${
                categoryFilter === cat
                  ? "bg-[#081A2E] text-white"
                  : "bg-slate-100 text-slate-600 hover:bg-slate-200"
              }`}
            >
              {cat}
            </button>
          ))}
        </div>
      </div>

      {/* Holidays Table */}
      <div className="bg-white rounded-xl border border-slate-200 shadow-xs overflow-hidden">
        <div className="overflow-x-auto">
          <table className="w-full text-left text-xs">
            <thead className="bg-[#081A2E] text-slate-200 uppercase tracking-wider text-[10px]">
              <tr>
                <th className="p-3.5">Holiday Name</th>
                <th className="p-3.5">Date & Duration</th>
                <th className="p-3.5">Day of Week</th>
                <th className="p-3.5">Classification</th>
                <th className="p-3.5">Days</th>
                <th className="p-3.5">Impact on Attendance Calculation</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-slate-100">
              {filtered.map((h) => (
                <tr key={h.id} className="hover:bg-slate-50/80 transition-colors">
                  <td className="p-3.5 font-bold text-slate-900">
                    {h.name}
                  </td>
                  <td className="p-3.5 font-semibold text-[#071A4D]">
                    {h.date}
                  </td>
                  <td className="p-3.5 text-slate-600">
                    {h.day}
                  </td>
                  <td className="p-3.5">
                    <span
                      className={`px-2.5 py-0.5 rounded-full font-bold text-[10px] uppercase ${
                        h.category === "NATIONAL"
                          ? "bg-blue-100 text-blue-900 border border-blue-200"
                          : h.category === "REGIONAL"
                          ? "bg-purple-100 text-purple-900 border border-purple-200"
                          : h.category === "DEPARTMENTAL"
                          ? "bg-amber-100 text-amber-900 border border-amber-200"
                          : "bg-emerald-100 text-emerald-900 border border-emerald-200"
                      }`}
                    >
                      {h.category}
                    </span>
                  </td>
                  <td className="p-3.5 font-bold text-slate-800">
                    {h.daysCount} Day{h.daysCount > 1 ? "s" : ""}
                  </td>
                  <td className="p-3.5 text-slate-600">
                    <span className="flex items-center gap-1.5 text-emerald-700 font-semibold">
                      <CheckCircle2 className="w-3.5 h-3.5" />
                      {h.impactOnAttendance}
                    </span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </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]">Declare Holiday</h3>
              <button onClick={() => setIsModalOpen(false)}>
                <X className="w-5 h-5 text-slate-400" />
              </button>
            </div>

            <form onSubmit={handleAddHoliday} className="space-y-4 pt-4 text-xs">
              <div>
                <label className="font-bold text-slate-800 block mb-1">Holiday Name *</label>
                <input
                  type="text"
                  placeholder="e.g. Saraswati Puja"
                  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>
                <label className="font-bold text-slate-800 block mb-1">Date or Range *</label>
                <input
                  type="text"
                  placeholder="e.g. 14 Feb 2025"
                  value={formDate}
                  onChange={(e) => setFormDate(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">Day of Week</label>
                  <input
                    type="text"
                    value={formDay}
                    onChange={(e) => setFormDay(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">Category</label>
                  <select
                    value={formCategory}
                    onChange={(e) => setFormCategory(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="NATIONAL">National Holiday</option>
                    <option value="REGIONAL">Regional Holiday</option>
                    <option value="INSTITUTIONAL">Institutional Break</option>
                    <option value="DEPARTMENTAL">Departmental Training Day</option>
                  </select>
                </div>
              </div>

              <div>
                <label className="font-bold text-slate-800 block mb-1">Number of Days</label>
                <input
                  type="number"
                  value={formDaysCount}
                  onChange={(e) => setFormDaysCount(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 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]"
                >
                  Declare Holiday
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </div>
  );
}
