"use client";

import React, { useState } from "react";
import Link from "next/link";
import {
  Users,
  UserCheck,
  BookOpen,
  Calendar,
  Clock,
  HeartPulse,
  FileSpreadsheet,
  Layers,
  GraduationCap,
  CalendarHeart,
  Sliders,
  BarChart3,
  TrendingUp,
  AlertTriangle,
  CheckCircle2,
  ChevronRight,
  ArrowUpRight,
  Sparkles,
  UtensilsCrossed,
  DoorOpen,
  FileText,
  UserPlus,
} from "lucide-react";
import { useAuth } from "@/context/auth-context";

export default function DeptAdminDashboard() {
  const { user } = useAuth();
  const [selectedSemester, setSelectedSemester] = useState<string>("all");

  const quickStats = [
    {
      title: "Department Students",
      value: "384",
      subtext: "Across B.Sc, M.Sc & Diploma",
      icon: Users,
      trend: "+12 this session",
      color: "from-blue-600 to-indigo-700",
      accent: "text-blue-600 bg-blue-50",
    },
    {
      title: "Allocated Faculty",
      value: "14",
      subtext: "Chef Instructors & Lecturers",
      icon: UserCheck,
      trend: "100% Assigned",
      color: "from-[#C8A45D] to-[#99732B]",
      accent: "text-amber-700 bg-amber-50",
    },
    {
      title: "Average Attendance",
      value: "81.4%",
      subtext: "NCHMCT Target: >= 75%",
      icon: TrendingUp,
      trend: "+2.1% vs last month",
      color: "from-emerald-600 to-teal-700",
      accent: "text-emerald-700 bg-emerald-50",
    },
    {
      title: "Pending Medical Req.",
      value: "3",
      subtext: "Awaiting HOD approval",
      icon: HeartPulse,
      trend: "Action Required",
      color: "from-rose-600 to-pink-700",
      accent: "text-rose-700 bg-rose-50",
    },
  ];

  const todayClasses = [
    {
      time: "09:00 AM - 10:00 AM",
      subject: "BHM111: Food Production Foundation",
      type: "Theory",
      faculty: "Chef Anirban Roy (Sr. Lecturer)",
      room: "Lecture Hall 204",
      semester: "Sem 1 (Section A)",
      status: "COMPLETED",
      attendance: "64/68 (94%)",
    },
    {
      time: "10:00 AM - 01:00 PM",
      subject: "BHM111P: Basic Culinary Lab (Kitchen)",
      type: "Practical",
      faculty: "Chef Rajesh Sharma & Chef Amit Sen",
      room: "Basic Training Kitchen (BTK)",
      semester: "Sem 1 (Batch K1)",
      status: "IN_PROGRESS",
      attendance: "In Progress",
    },
    {
      time: "10:00 AM - 01:00 PM",
      subject: "BHM211P: Quantity Food Production Lab",
      type: "Practical",
      faculty: "Chef Meenakshi Iyer",
      room: "Quantity Food Kitchen (QFK)",
      semester: "Sem 3 (Batch Q1)",
      status: "IN_PROGRESS",
      attendance: "In Progress",
    },
    {
      time: "02:00 PM - 05:00 PM",
      subject: "BHM311P: Advanced Bakery & Confectionery",
      type: "Practical",
      faculty: "Chef David Rozario",
      room: "Bakery Studio Lab",
      semester: "Sem 5 (Batch B1)",
      status: "UPCOMING",
      attendance: "Pending",
    },
  ];

  const clientModules = [
    {
      title: "Academic Sessions",
      desc: "Manage term dates, teaching weeks & active session status",
      href: "/dept-admin/sessions",
      icon: Calendar,
      color: "bg-blue-50 text-blue-700 border-blue-200",
    },
    {
      title: "Course Management",
      desc: "Degree programs, credit hours & syllabus modules",
      href: "/dept-admin/courses",
      icon: GraduationCap,
      color: "bg-amber-50 text-amber-700 border-amber-200",
    },
    {
      title: "Semester Management",
      desc: "Term progression, active cohorts & working day counts",
      href: "/dept-admin/semesters",
      icon: Layers,
      color: "bg-emerald-50 text-emerald-700 border-emerald-200",
    },
    {
      title: "Subject Management",
      desc: "Theory, kitchen practicals & lab credits catalog",
      href: "/dept-admin/subjects",
      icon: BookOpen,
      color: "bg-indigo-50 text-indigo-700 border-indigo-200",
    },
    {
      title: "Faculty Allocation",
      desc: "Workload distribution & course teacher mapping",
      href: "/dept-admin/faculty-allocation",
      icon: UserCheck,
      color: "bg-purple-50 text-purple-700 border-purple-200",
    },
    {
      title: "Student Registration",
      desc: "Roster enrollment, batch groups & admissions",
      href: "/dept-admin/students",
      icon: UserPlus,
      color: "bg-teal-50 text-teal-700 border-teal-200",
    },
    {
      title: "Group Management",
      desc: "Kitchen batches, practical teams & theory sections",
      href: "/dept-admin/groups",
      icon: Users,
      color: "bg-cyan-50 text-cyan-700 border-cyan-200",
    },
    {
      title: "Timetable Management",
      desc: "Weekly master timetable & kitchen lab slots",
      href: "/dept-admin/timetable",
      icon: Clock,
      color: "bg-orange-50 text-orange-700 border-orange-200",
    },
    {
      title: "Holiday Calendar",
      desc: "Gazetted, regional & institute declared breaks",
      href: "/dept-admin/holidays",
      icon: CalendarHeart,
      color: "bg-rose-50 text-rose-700 border-rose-200",
    },
    {
      title: "Attendance Rules",
      desc: "75% NCHMCT thresholds, condonation & lock policy",
      href: "/dept-admin/attendance-rules",
      icon: Sliders,
      color: "bg-slate-100 text-slate-800 border-slate-300",
    },
    {
      title: "Medical Adjustments",
      desc: "Verify leaves, certificates & medical duty credits",
      href: "/dept-admin/medical-adjustments",
      icon: HeartPulse,
      badge: "3 New",
      color: "bg-pink-50 text-pink-700 border-pink-200",
    },
    {
      title: "Reports",
      desc: "Defaulter reports, subject matrices & daily registers",
      href: "/dept-admin/reports",
      icon: BarChart3,
      color: "bg-violet-50 text-violet-700 border-violet-200",
    },
    {
      title: "APR Generation",
      desc: "Official Annual Performance & Attendance register",
      href: "/dept-admin/apr",
      icon: FileSpreadsheet,
      badge: "NCHMCT Ready",
      color: "bg-amber-100 text-amber-900 border-amber-300",
    },
  ];

  return (
    <div className="p-4 sm:p-6 lg:p-8 space-y-6 max-w-7xl mx-auto">
      {/* ========================================================================= */}
      {/* 1. HERO BANNER                                                            */}
      {/* ========================================================================= */}
      <div className="relative overflow-hidden rounded-2xl bg-gradient-to-r from-[#081A2E] via-[#0F2942] to-[#1A3D63] p-6 sm:p-8 text-white shadow-xl border border-[#1E3A5F]">
        <div className="relative z-10 flex flex-col md:flex-row md:items-center justify-between gap-6">
          <div className="space-y-2">
            <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-[#C8A45D]/20 border border-[#C8A45D]/50 text-amber-200 text-xs font-bold uppercase tracking-wider">
              <Sparkles className="w-3.5 h-3.5 text-[#C8A45D]" />
              Academic & Department Administrator Console
            </div>
            <h1 className="text-2xl sm:text-3xl font-extrabold tracking-tight">
              Food Production & Culinary Arts
            </h1>
            <p className="text-slate-300 text-sm max-w-2xl">
              Welcome, <strong className="text-white">{user?.name || "Department Administrator"}</strong>. Overseeing academic sessions, faculty allocations, timetable, kitchen practicals, attendance rules, and NCHMCT APR compliance.
            </p>
          </div>

          <div className="flex flex-wrap items-center gap-2.5">
            <Link
              href="/dept-admin/timetable"
              className="px-4 py-2.5 rounded-lg bg-[#C8A45D] hover:bg-[#B38F48] text-slate-950 font-bold text-xs shadow-md transition-all flex items-center gap-1.5"
            >
              <Clock className="w-4 h-4" />
              <span>Department Timetable</span>
            </Link>
            <Link
              href="/dept-admin/apr"
              className="px-4 py-2.5 rounded-lg bg-white/10 hover:bg-white/20 text-white font-bold text-xs border border-white/20 transition-all flex items-center gap-1.5"
            >
              <FileSpreadsheet className="w-4 h-4 text-[#C8A45D]" />
              <span>Generate APR</span>
            </Link>
          </div>
        </div>
      </div>

      {/* ========================================================================= */}
      {/* 2. QUICK STATS CARDS                                                      */}
      {/* ========================================================================= */}
      <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
        {quickStats.map((stat, i) => {
          const Icon = stat.icon;
          return (
            <div
              key={i}
              className="p-5 rounded-xl bg-white border border-slate-200 shadow-xs hover:shadow-md transition-all space-y-3"
            >
              <div className="flex items-center justify-between">
                <span className="text-xs font-semibold text-slate-500 uppercase tracking-wider">
                  {stat.title}
                </span>
                <div className={`p-2 rounded-lg ${stat.accent}`}>
                  <Icon className="w-4 h-4" />
                </div>
              </div>
              <div>
                <div className="text-2xl font-black text-[#071A4D]">{stat.value}</div>
                <div className="text-xs text-slate-500 mt-0.5">{stat.subtext}</div>
              </div>
              <div className="pt-2 border-t border-slate-100 flex items-center justify-between text-[11px] font-medium">
                <span className="text-slate-600">{stat.trend}</span>
                <span className="text-[#C8A45D] font-bold">Details →</span>
              </div>
            </div>
          );
        })}
      </div>

      {/* ========================================================================= */}
      {/* 3. TODAY'S KITCHEN & LECTURE CLASSES                                      */}
      {/* ========================================================================= */}
      <div className="bg-white rounded-xl border border-slate-200 shadow-xs overflow-hidden">
        <div className="p-5 border-b border-slate-200 flex flex-col sm:flex-row sm:items-center justify-between gap-3 bg-slate-50/50">
          <div>
            <h2 className="text-base font-bold text-[#071A4D] flex items-center gap-2">
              <UtensilsCrossed className="w-4 h-4 text-[#C8A45D]" />
              Today&apos;s Department Classes & Practical Labs
            </h2>
            <p className="text-xs text-slate-500 mt-0.5">
              Live monitoring of theory lectures and intensive 3-hour kitchen practicals
            </p>
          </div>

          <Link
            href="/dept-admin/timetable"
            className="text-xs font-bold text-[#1769E8] hover:underline flex items-center gap-1"
          >
            <span>Full Master Schedule</span>
            <ArrowUpRight className="w-3.5 h-3.5" />
          </Link>
        </div>

        <div className="divide-y divide-slate-100">
          {todayClasses.map((cls, idx) => (
            <div
              key={idx}
              className="p-4 sm:p-5 flex flex-col md:flex-row md:items-center justify-between gap-4 hover:bg-slate-50/70 transition-colors"
            >
              <div className="flex items-start sm:items-center gap-3">
                <div className="w-10 h-10 rounded-lg bg-slate-100 flex items-center justify-center shrink-0 border border-slate-200 text-slate-700 font-bold text-xs">
                  {cls.type === "Practical" ? "LAB" : "TH"}
                </div>
                <div>
                  <div className="font-bold text-sm text-slate-900">{cls.subject}</div>
                  <div className="text-xs text-slate-500 flex flex-wrap items-center gap-3 mt-1">
                    <span className="font-semibold text-slate-700">{cls.faculty}</span>
                    <span>•</span>
                    <span className="flex items-center gap-1">
                      <DoorOpen className="w-3 h-3 text-slate-400" />
                      {cls.room}
                    </span>
                    <span>•</span>
                    <span className="font-medium text-[#785E2F]">{cls.semester}</span>
                  </div>
                </div>
              </div>

              <div className="flex items-center justify-between md:justify-end gap-4 shrink-0">
                <div className="text-right">
                  <div className="text-xs font-mono font-bold text-slate-700">{cls.time}</div>
                  <div className="text-[11px] text-slate-500 mt-0.5">{cls.attendance}</div>
                </div>

                <span
                  className={`text-[10px] font-bold px-2.5 py-1 rounded-full uppercase ${
                    cls.status === "COMPLETED"
                      ? "bg-emerald-100 text-emerald-800"
                      : cls.status === "IN_PROGRESS"
                      ? "bg-amber-100 text-amber-800 animate-pulse"
                      : "bg-slate-100 text-slate-600"
                  }`}
                >
                  {cls.status === "COMPLETED"
                    ? "Marked"
                    : cls.status === "IN_PROGRESS"
                    ? "In Session"
                    : "Scheduled"}
                </span>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* ========================================================================= */}
      {/* 4. CLIENT ROLE MODULES (IHM_UI_Design_Style.md §35-48)                    */}
      {/* ========================================================================= */}
      <div>
        <div className="mb-4">
          <h2 className="text-base font-bold text-[#071A4D] flex items-center gap-2">
            <BookOpen className="w-4 h-4 text-[#C8A45D]" />
            Department Administrator Modules & Roles
          </h2>
          <p className="text-xs text-slate-500 mt-0.5">
            Official operational areas specified for the Academic / Department Administrator role
          </p>
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
          {clientModules.map((mod, i) => {
            const Icon = mod.icon;
            return (
              <Link
                key={i}
                href={mod.href}
                className="group p-4 rounded-xl bg-white border border-slate-200 shadow-xs hover:shadow-md hover:border-[#C8A45D] transition-all flex flex-col justify-between"
              >
                <div>
                  <div className="flex items-center justify-between mb-3">
                    <div className={`p-2.5 rounded-lg border ${mod.color}`}>
                      <Icon className="w-5 h-5" />
                    </div>
                    {mod.badge && (
                      <span className="text-[10px] font-bold px-2 py-0.5 rounded-full bg-rose-50 text-rose-700 border border-rose-200">
                        {mod.badge}
                      </span>
                    )}
                  </div>
                  <h3 className="font-bold text-sm text-[#071A4D] group-hover:text-[#1769E8] transition-colors">
                    {mod.title}
                  </h3>
                  <p className="text-xs text-slate-500 mt-1 line-clamp-2">{mod.desc}</p>
                </div>

                <div className="pt-3 mt-3 border-t border-slate-100 flex items-center justify-between text-xs font-semibold text-[#785E2F] group-hover:text-[#1769E8]">
                  <span>Access Module</span>
                  <ChevronRight className="w-4 h-4 transition-transform group-hover:translate-x-1" />
                </div>
              </Link>
            );
          })}
        </div>
      </div>

      {/* ========================================================================= */}
      {/* 5. SEMESTER ATTENDANCE STATUS & NCHMCT COMPLIANCE                          */}
      {/* ========================================================================= */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div className="lg:col-span-2 bg-white rounded-xl border border-slate-200 p-5 shadow-xs space-y-4">
          <div className="flex items-center justify-between">
            <div>
              <h3 className="font-bold text-sm text-[#071A4D]">
                Department Attendance by Semester
              </h3>
              <p className="text-xs text-slate-500">
                Tracking against mandatory 75% NCHMCT examination eligibility
              </p>
            </div>
            <Link
              href="/dept-admin/reports"
              className="text-xs font-bold text-[#1769E8] hover:underline"
            >
              Detailed Reports →
            </Link>
          </div>

          <div className="space-y-4">
            <div>
              <div className="flex justify-between text-xs font-bold mb-1">
                <span className="text-slate-700">Semester 1 (Freshers - 138 Students)</span>
                <span className="text-emerald-700 font-mono">84.2%</span>
              </div>
              <div className="w-full bg-slate-100 h-2.5 rounded-full overflow-hidden">
                <div className="bg-emerald-500 h-full rounded-full" style={{ width: "84.2%" }} />
              </div>
              <div className="flex justify-between text-[10px] text-slate-400 mt-1">
                <span>Safe Zone (&gt;= 75%)</span>
                <span>4 Defaulters currently</span>
              </div>
            </div>

            <div>
              <div className="flex justify-between text-xs font-bold mb-1">
                <span className="text-slate-700">Semester 3 (Intermediate - 124 Students)</span>
                <span className="text-emerald-700 font-mono">79.8%</span>
              </div>
              <div className="w-full bg-slate-100 h-2.5 rounded-full overflow-hidden">
                <div className="bg-emerald-500 h-full rounded-full" style={{ width: "79.8%" }} />
              </div>
              <div className="flex justify-between text-[10px] text-slate-400 mt-1">
                <span>Safe Zone (&gt;= 75%)</span>
                <span>8 Defaulters currently</span>
              </div>
            </div>

            <div>
              <div className="flex justify-between text-xs font-bold mb-1">
                <span className="text-slate-700">Semester 5 (Final Year - 122 Students)</span>
                <span className="text-amber-700 font-mono">80.5%</span>
              </div>
              <div className="w-full bg-slate-100 h-2.5 rounded-full overflow-hidden">
                <div className="bg-[#C8A45D] h-full rounded-full" style={{ width: "80.5%" }} />
              </div>
              <div className="flex justify-between text-[10px] text-slate-400 mt-1">
                <span>Safe Zone (&gt;= 75%)</span>
                <span>6 Defaulters currently</span>
              </div>
            </div>
          </div>
        </div>

        {/* Action Panel */}
        <div className="bg-[#0B2544] text-white rounded-xl p-5 shadow-xs border border-[#1E3A5F] flex flex-col justify-between">
          <div className="space-y-3">
            <div className="w-9 h-9 rounded-lg bg-[#C8A45D]/20 border border-[#C8A45D]/40 flex items-center justify-center">
              <CheckCircle2 className="w-5 h-5 text-[#C8A45D]" />
            </div>
            <h3 className="font-bold text-base text-white">Monthly APR Register</h3>
            <p className="text-xs text-slate-300">
              The monthly Attendance Progress Register (APR) for October is ready for compilation and department review.
            </p>
          </div>

          <div className="pt-4 border-t border-white/10 space-y-2 mt-4">
            <Link
              href="/dept-admin/apr"
              className="w-full py-2.5 px-3 rounded-lg bg-[#C8A45D] hover:bg-[#B38F48] text-slate-950 font-bold text-xs text-center block transition-all shadow-sm"
            >
              Open APR Generation Engine
            </Link>
            <Link
              href="/dept-admin/medical-adjustments"
              className="w-full py-2 px-3 rounded-lg bg-white/10 hover:bg-white/15 text-white font-semibold text-xs text-center block transition-colors"
            >
              Review 3 Medical Requests
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
}
