"use client";

import React, { useState, useRef, useEffect } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import {
  Home,
  Calendar,
  GraduationCap,
  Layers,
  BookOpen,
  UserCheck,
  UserPlus,
  Users,
  Clock,
  CalendarHeart,
  Sliders,
  HeartPulse,
  BarChart3,
  FileSpreadsheet,
  LogOut,
  Award,
  ChevronDown,
  Bell,
  Search,
  Sparkles,
  Menu,
  X,
  Building2,
  ShieldCheck,
  CheckCircle2,
  AlertTriangle,
  ChevronRight,
  Filter,
} from "lucide-react";
import { RouteGuard } from "@/components/auth/route-guard";
import { useAuth } from "@/context/auth-context";
import { SidebarBuildingFooter } from "@/components/layout/sidebar-building-footer";
import { cn } from "@/lib/utils";
import { toast } from "sonner";

interface NavItem {
  label: string;
  href: string;
  icon: React.ElementType;
  badge?: string;
  badgeColor?: string;
}

// 13 Canonical Modules for Academic / Department Administrator matching IHM_UI_Design_Style.md §35-48
const deptAdminNavigation: NavItem[] = [
  {
    label: "Dashboard",
    href: "/dept-admin/dashboard",
    icon: Home,
  },
  {
    label: "Academic Sessions",
    href: "/dept-admin/sessions",
    icon: Calendar,
  },
  {
    label: "Course Management",
    href: "/dept-admin/courses",
    icon: GraduationCap,
  },
  {
    label: "Semester Management",
    href: "/dept-admin/semesters",
    icon: Layers,
  },
  {
    label: "Subject Management",
    href: "/dept-admin/subjects",
    icon: BookOpen,
  },
  {
    label: "Faculty Allocation",
    href: "/dept-admin/faculty-allocation",
    icon: UserCheck,
  },
  {
    label: "Student Registration",
    href: "/dept-admin/students",
    icon: UserPlus,
  },
  {
    label: "Group Management",
    href: "/dept-admin/groups",
    icon: Users,
  },
  {
    label: "Timetable Management",
    href: "/dept-admin/timetable",
    icon: Clock,
  },
  {
    label: "Holiday Calendar",
    href: "/dept-admin/holidays",
    icon: CalendarHeart,
  },
  {
    label: "Attendance Rules",
    href: "/dept-admin/attendance-rules",
    icon: Sliders,
  },
  {
    label: "Medical Adjustments",
    href: "/dept-admin/medical-adjustments",
    icon: HeartPulse,
    badge: "3",
    badgeColor: "bg-rose-500 text-white",
  },
  {
    label: "Reports",
    href: "/dept-admin/reports",
    icon: BarChart3,
  },
  {
    label: "APR Generation",
    href: "/dept-admin/apr",
    icon: FileSpreadsheet,
    badge: "New",
    badgeColor: "bg-[#F4B400] text-[#081A2E] font-bold",
  },
];

const DEPARTMENTS = [
  "Food Production & Culinary Arts",
  "Food & Beverage Service",
  "Front Office Operations",
  "Accommodation Operations (Housekeeping)",
  "Bakery & Confectionery",
  "Academic Affairs",
];

export default function DeptAdminLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const pathname = usePathname();
  const { user, logout } = useAuth();
  const [mobileMenuOpen, setMobileMenuOpen] = useState(false);
  const [userDropdownOpen, setUserDropdownOpen] = useState(false);
  const [deptDropdownOpen, setDeptDropdownOpen] = useState(false);
  const [notificationOpen, setNotificationOpen] = useState(false);
  const [selectedDept, setSelectedDept] = useState("Food Production & Culinary Arts");

  const dropdownRef = useRef<HTMLDivElement>(null);
  const deptRef = useRef<HTMLDivElement>(null);
  const notifRef = useRef<HTMLDivElement>(null);

  // Close dropdowns on outside click
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setUserDropdownOpen(false);
      }
      if (deptRef.current && !deptRef.current.contains(event.target as Node)) {
        setDeptDropdownOpen(false);
      }
      if (notifRef.current && !notifRef.current.contains(event.target as Node)) {
        setNotificationOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  // Close mobile drawer on route navigation
  useEffect(() => {
    setMobileMenuOpen(false);
  }, [pathname]);

  const handleLogout = async () => {
    await logout();
  };

  const handleDeptChange = (dept: string) => {
    setSelectedDept(dept);
    setDeptDropdownOpen(false);
    toast.success(`Active Department: ${dept}`);
  };

  return (
    <RouteGuard allowedRoles={["DEPARTMENT_ADMIN", "ACADEMIC_ADMIN", "SUPER_ADMIN"]}>
      <div className="flex h-screen bg-[#F8FAFC] text-slate-800 font-sans overflow-hidden">
        {/* ========================================================================= */}
        {/* DESKTOP SIDEBAR                                                           */}
        {/* ========================================================================= */}
        <aside
          style={{ ["--sidebar-active" as string]: "#F4B400" }}
          className="hidden lg:flex flex-col justify-between w-[220px] h-screen lg:sticky lg:top-0 bg-[#081A2E] text-[#F5F7FA] border-r border-[#0d2238] shrink-0 z-30 shadow-xl relative"
        >
          {/* Institution Header Brand */}
          <div className="p-4 border-b border-[#1E3A5F] flex items-center justify-between bg-[#051322]">
            <Link href="/dept-admin/dashboard" className="flex items-center gap-2.5 group">
              <div className="w-9 h-9 rounded-full border border-[#D99A24] bg-[#081A2E] flex items-center justify-center shrink-0 shadow-md group-hover:scale-105 transition-transform">
                <Award className="w-4.5 h-4.5 text-[#D99A24]" />
              </div>
              <div>
                <span className="text-[9px] font-bold tracking-[0.16em] uppercase text-[#CBD5E1] block">
                  IHM KOLKATA
                </span>
                <span className="text-[11px] font-extrabold uppercase tracking-wide text-white block">
                  Dept Admin
                </span>
                <span className="text-[9px] font-medium text-[#D99A24] block truncate max-w-[120px]">
                  Academic Admin
                </span>
              </div>
            </Link>
          </div>

          {/* Department Indicator Badge in Sidebar */}
          <div className="px-3.5 py-2.5 bg-[#0B2544]/60 border-b border-[#1E3A5F]/70 flex items-center justify-between text-xs">
            <div className="flex items-center gap-2 overflow-hidden">
              <Building2 className="w-3.5 h-3.5 text-[#C8A45D] shrink-0" />
              <div className="truncate">
                <span className="text-[9px] text-slate-400 uppercase font-semibold block">Active Department</span>
                <span className="text-[10.5px] font-bold text-amber-100 truncate block">{selectedDept}</span>
              </div>
            </div>
          </div>

          {/* Sidebar Navigation Items */}
          <nav className="flex-1 overflow-y-auto min-h-0 p-2 space-y-0.5 [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden no-scrollbar pb-3">
            <div className="px-2.5 pt-1.5 pb-1 text-[9.5px] font-bold uppercase tracking-wider text-slate-400">
              Department Operations
            </div>

            {deptAdminNavigation.map((item) => {
              const Icon = item.icon;
              const isActive =
                pathname === item.href ||
                (item.href !== "/dept-admin/dashboard" && pathname.startsWith(item.href));

              return (
                <Link
                  key={item.href}
                  href={item.href}
                  className={cn(
                    "flex items-center justify-between px-3.5 py-2.5 rounded-lg text-xs font-medium transition-all group",
                    isActive
                      ? "bg-[#F4B400] text-[#081A2E] font-semibold shadow-xs"
                      : "text-[#F5F7FA] hover:bg-white/5 hover:text-white font-medium"
                  )}
                >
                  <div className="flex items-center gap-3">
                    <Icon
                      className={cn(
                        "w-4 h-4 shrink-0 transition-transform group-hover:scale-110",
                        isActive ? "text-[#081A2E]" : "text-[#D99A24]"
                      )}
                    />
                    <span className="truncate">{item.label}</span>
                  </div>

                  {item.badge && (
                    <span
                      className={cn(
                        "text-[10px] px-1.5 py-0.5 rounded-full font-bold uppercase shrink-0",
                        item.badgeColor || (isActive ? "bg-[#081A2E] text-[#F4B400]" : "bg-[#F4B400] text-[#081A2E]")
                      )}
                    >
                      {item.badge}
                    </span>
                  )}
                </Link>
              );
            })}
          </nav>

          {/* Sidebar Architectural Building Branding Footer */}
          <SidebarBuildingFooter />
        </aside>

        {/* ========================================================================= */}
        {/* MAIN APPLICATION AREA                                                    */}
        {/* ========================================================================= */}
        <div className="flex-1 flex flex-col min-w-0 overflow-hidden">
          {/* TOP NAVBAR */}
          <header className="h-16 bg-white border-b border-[#E2E8F0] px-4 sm:px-6 flex items-center justify-between shrink-0 z-20 shadow-xs">
            {/* Mobile Hamburger + Title */}
            <div className="flex items-center gap-3">
              <button
                onClick={() => setMobileMenuOpen(true)}
                className="lg:hidden p-2 text-slate-600 hover:text-slate-900 hover:bg-slate-100 rounded-lg"
                aria-label="Open sidebar"
              >
                <Menu className="w-5 h-5" />
              </button>

              {/* Department Switcher Dropdown */}
              <div className="relative" ref={deptRef}>
                <button
                  onClick={() => setDeptDropdownOpen(!deptDropdownOpen)}
                  className="flex items-center gap-2 px-3 py-1.5 rounded-lg bg-amber-50/70 border border-amber-200 text-xs font-bold text-[#785E2F] hover:bg-amber-100/70 transition-colors"
                >
                  <Building2 className="w-3.5 h-3.5 text-[#C8A45D]" />
                  <span className="max-w-[170px] sm:max-w-xs truncate">{selectedDept}</span>
                  <ChevronDown className="w-3.5 h-3.5 text-[#785E2F]" />
                </button>

                {deptDropdownOpen && (
                  <div className="absolute left-0 mt-2 w-72 bg-white rounded-xl shadow-xl border border-slate-200 py-1.5 z-50 animate-in fade-in slide-in-from-top-2 duration-150">
                    <div className="px-3 py-2 border-b border-slate-100 text-[10px] font-bold text-slate-400 uppercase tracking-wider">
                      Switch Active Department
                    </div>
                    {DEPARTMENTS.map((dept) => (
                      <button
                        key={dept}
                        onClick={() => handleDeptChange(dept)}
                        className={cn(
                          "w-full text-left px-3.5 py-2.5 text-xs transition-colors flex items-center justify-between",
                          selectedDept === dept
                            ? "bg-amber-50 text-[#785E2F] font-bold"
                            : "text-slate-700 hover:bg-slate-50"
                        )}
                      >
                        <span className="truncate">{dept}</span>
                        {selectedDept === dept && (
                          <CheckCircle2 className="w-3.5 h-3.5 text-[#C8A45D] shrink-0" />
                        )}
                      </button>
                    ))}
                  </div>
                )}
              </div>
            </div>

            {/* Right Header Actions */}
            <div className="flex items-center gap-2 sm:gap-4">
              {/* Notifications Popover */}
              <div className="relative" ref={notifRef}>
                <button
                  onClick={() => setNotificationOpen(!notificationOpen)}
                  className="relative p-2 text-slate-600 hover:text-slate-900 hover:bg-slate-100 rounded-lg transition-colors"
                  aria-label="Notifications"
                >
                  <Bell className="w-5 h-5" />
                  <span className="absolute top-1.5 right-1.5 w-2 h-2 rounded-full bg-rose-500 animate-pulse" />
                </button>

                {notificationOpen && (
                  <div className="absolute right-0 mt-2 w-80 sm:w-96 bg-white rounded-xl shadow-xl border border-slate-200 p-4 z-50 animate-in fade-in slide-in-from-top-2 duration-150">
                    <div className="flex items-center justify-between pb-3 border-b border-slate-100">
                      <div className="font-bold text-sm text-[#071A4D]">Department Alerts</div>
                      <span className="text-[11px] bg-rose-100 text-rose-700 font-bold px-2 py-0.5 rounded-full">
                        3 Pending
                      </span>
                    </div>
                    <div className="divide-y divide-slate-100 text-xs py-1 max-h-72 overflow-y-auto">
                      <div className="py-2.5 flex items-start gap-2.5">
                        <AlertTriangle className="w-4 h-4 text-amber-500 shrink-0 mt-0.5" />
                        <div>
                          <div className="font-semibold text-slate-800">3 Medical Leave Requests Pending</div>
                          <div className="text-[11px] text-slate-500 mt-0.5">Sem 3 Kitchen batch students awaiting HOD approval.</div>
                        </div>
                      </div>
                      <div className="py-2.5 flex items-start gap-2.5">
                        <Clock className="w-4 h-4 text-indigo-500 shrink-0 mt-0.5" />
                        <div>
                          <div className="font-semibold text-slate-800">Weekly Timetable Finalized</div>
                          <div className="text-[11px] text-slate-500 mt-0.5">Odd Semester 2024-25 timetable published.</div>
                        </div>
                      </div>
                      <div className="py-2.5 flex items-start gap-2.5">
                        <CheckCircle2 className="w-4 h-4 text-emerald-500 shrink-0 mt-0.5" />
                        <div>
                          <div className="font-semibold text-slate-800">Monthly APR Register Ready</div>
                          <div className="text-[11px] text-slate-500 mt-0.5">October APR generated for NCHMCT compliance.</div>
                        </div>
                      </div>
                    </div>
                    <div className="pt-2 border-t border-slate-100 text-center">
                      <Link
                        href="/dept-admin/medical-adjustments"
                        onClick={() => setNotificationOpen(false)}
                        className="text-xs font-bold text-[#1769E8] hover:underline"
                      >
                        View all pending medical adjustments →
                      </Link>
                    </div>
                  </div>
                )}
              </div>

              {/* Profile Dropdown */}
              <div className="relative" ref={dropdownRef}>
                <button
                  onClick={() => setUserDropdownOpen(!userDropdownOpen)}
                  className="flex items-center gap-2.5 p-1.5 rounded-lg hover:bg-slate-100 transition-colors"
                >
                  <div className="w-8 h-8 rounded-full bg-[#081A2E] border border-[#C8A45D] text-[#C8A45D] font-bold text-xs flex items-center justify-center shrink-0">
                    {user?.name ? user.name.charAt(0).toUpperCase() : "D"}
                  </div>
                  <div className="hidden md:block text-left">
                    <span className="text-xs font-bold text-slate-900 block truncate max-w-[130px]">
                      {user?.name || "Chef Rajesh Sharma"}
                    </span>
                    <span className="text-[10px] text-slate-500 block">
                      Department Administrator
                    </span>
                  </div>
                  <ChevronDown className="w-3.5 h-3.5 text-slate-400" />
                </button>

                {userDropdownOpen && (
                  <div className="absolute right-0 mt-2 w-64 bg-white rounded-xl shadow-xl border border-slate-200 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150">
                    <div className="px-4 py-2.5 border-b border-slate-100">
                      <div className="text-xs font-bold text-[#071A4D] truncate">
                        {user?.name || "Department Administrator"}
                      </div>
                      <div className="text-[11px] text-slate-500 truncate">
                        {user?.email || ""}
                      </div>
                      <div className="mt-1.5 inline-block text-[10px] font-bold bg-[#FBF4E4] text-[#8C6D28] border border-[#C8A45D] px-2 py-0.5 rounded-full">
                        Academic / Dept Admin
                      </div>
                    </div>

                    <div className="py-1 text-xs">
                      <Link
                        href="/dept-admin/dashboard"
                        onClick={() => setUserDropdownOpen(false)}
                        className="block px-4 py-2 text-slate-700 hover:bg-slate-50"
                      >
                        Department Overview
                      </Link>
                      <Link
                        href="/dept-admin/attendance-rules"
                        onClick={() => setUserDropdownOpen(false)}
                        className="block px-4 py-2 text-slate-700 hover:bg-slate-50"
                      >
                        Attendance Rules Configuration
                      </Link>
                      <Link
                        href="/dept-admin/apr"
                        onClick={() => setUserDropdownOpen(false)}
                        className="block px-4 py-2 text-slate-700 hover:bg-slate-50"
                      >
                        APR Generation Console
                      </Link>
                    </div>

                    <div className="pt-1 border-t border-slate-100">
                      <button
                        onClick={handleLogout}
                        className="w-full text-left px-4 py-2 text-xs font-semibold text-rose-600 hover:bg-rose-50 flex items-center gap-2"
                      >
                        <LogOut className="w-3.5 h-3.5" />
                        <span>Sign Out</span>
                      </button>
                    </div>
                  </div>
                )}
              </div>
            </div>
          </header>

          {/* PAGE CONTENT CONTAINER */}
          <main className="flex-1 overflow-y-auto bg-[#F8FAFC]">
            {children}
          </main>
        </div>

        {/* ========================================================================= */}
        {/* MOBILE SIDEBAR DRAWER                                                     */}
        {/* ========================================================================= */}
        {mobileMenuOpen && (
          <div className="fixed inset-0 z-50 lg:hidden flex">
            {/* Backdrop */}
            <div
              className="fixed inset-0 bg-slate-900/60 backdrop-blur-xs transition-opacity"
              onClick={() => setMobileMenuOpen(false)}
            />

            {/* Drawer */}
            <div className="relative w-80 max-w-[85vw] bg-[#081A2E] text-slate-200 flex flex-col h-full shadow-2xl z-10">
              <div className="p-4 border-b border-[#1E3A5F] flex items-center justify-between bg-[#051322]">
                <div className="flex items-center gap-2.5">
                  <div className="w-9 h-9 rounded-full border-2 border-[#C8A45D] bg-[#081A2E] flex items-center justify-center">
                    <Award className="w-4 h-4 text-[#C8A45D]" />
                  </div>
                  <div>
                    <span className="text-[10px] font-bold text-[#C8A45D] block tracking-wider uppercase">
                      IHM KOLKATA
                    </span>
                    <span className="text-xs font-extrabold text-white block uppercase">
                      Dept Admin Console
                    </span>
                  </div>
                </div>
                <button
                  onClick={() => setMobileMenuOpen(false)}
                  className="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-white/10"
                >
                  <X className="w-5 h-5" />
                </button>
              </div>

              {/* Navigation */}
              <nav className="flex-1 overflow-y-auto p-3 space-y-1 [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden no-scrollbar">
                {deptAdminNavigation.map((item) => {
                  const Icon = item.icon;
                  const isActive =
                    pathname === item.href ||
                    (item.href !== "/dept-admin/dashboard" && pathname.startsWith(item.href));

                  return (
                    <Link
                      key={item.href}
                      href={item.href}
                      className={cn(
                        "flex items-center justify-between px-3.5 py-2.5 rounded-lg text-xs font-medium transition-colors",
                        isActive
                          ? "bg-[#F4B400] text-[#081A2E] font-semibold shadow-xs"
                          : "text-[#F5F7FA] hover:bg-white/5 hover:text-white font-medium"
                      )}
                    >
                      <div className="flex items-center gap-3">
                        <Icon className={cn("w-4 h-4", isActive ? "text-[#081A2E]" : "text-[#D99A24]")} />
                        <span>{item.label}</span>
                      </div>
                      {item.badge && (
                        <span
                          className={cn(
                            "text-[10px] px-1.5 py-0.5 rounded-full font-bold uppercase",
                            item.badgeColor || (isActive ? "bg-[#081A2E] text-[#F4B400]" : "bg-[#F4B400] text-[#081A2E]")
                          )}
                        >
                          {item.badge}
                        </span>
                      )}
                    </Link>
                  );
                })}
              </nav>

              {/* Sign out footer */}
              <div className="p-3 border-t border-[#1E3A5F]">
                <button
                  onClick={handleLogout}
                  className="w-full flex items-center justify-center gap-2 py-2.5 px-3 rounded-lg bg-rose-500/10 text-rose-300 hover:bg-rose-500/20 text-xs font-bold transition-colors"
                >
                  <LogOut className="w-4 h-4" />
                  <span>Sign Out</span>
                </button>
              </div>
            </div>
          </div>
        )}
      </div>
    </RouteGuard>
  );
}
