"use client";

import React, { useState, useRef, useEffect } from "react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import {
  Home,
  BookOpen,
  CalendarDays,
  FileSpreadsheet,
  LogOut,
  Award,
  ChevronDown,
  Bell,
  Clock,
  Layers,
  GraduationCap,
  CheckCircle2,
  Search,
  Sparkles,
  Users,
  Menu,
  X,
  History,
  HeartPulse,
  FileText,
  BarChart3,
  PieChart,
  ShieldAlert,
  AlertTriangle,
  FileCheck,
} 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 SubmenuItem {
  title: string;
  href: string;
  icon?: React.ElementType;
}

interface NavItem {
  label: string;
  href: string;
  icon: React.ElementType;
  submenus?: SubmenuItem[];
}

// Student Navigation Structure matching Admin & Faculty Sidebar UI
const studentNavigation: NavItem[] = [
  {
    label: "Dashboard",
    href: "/student/dashboard",
    icon: Home,
  },
  {
    label: "Attendance Analytics",
    href: "/student/attendance/overall",
    icon: BarChart3,
    submenus: [
      { title: "Overall Attendance", href: "/student/attendance/overall", icon: PieChart },
      { title: "Subject-wise Attendance", href: "/student/attendance/subjects", icon: BookOpen },
      { title: "Theory Attendance", href: "/student/attendance/theory", icon: FileText },
      { title: "Practical Attendance", href: "/student/attendance/practical", icon: Award },
    ],
  },
  {
    label: "Session Logs & History",
    href: "/student/history",
    icon: CalendarDays,
    submenus: [
      { title: "Attendance History", href: "/student/history", icon: History },
    ],
  },
  {
    label: "Adjustments & Leave",
    href: "/student/adjustments/medical",
    icon: HeartPulse,
    submenus: [
      { title: "Medical Adjustment", href: "/student/adjustments/medical", icon: HeartPulse },
      { title: "Condonation Requests", href: "/student/adjustments/condonation", icon: FileCheck },
    ],
  },
  {
    label: "Notices & Circulars",
    href: "/student/notices",
    icon: Bell,
    submenus: [
      { title: "Official Notices", href: "/student/notices", icon: Bell },
    ],
  },
  {
    label: "Reports & Certificates",
    href: "/student/reports",
    icon: FileSpreadsheet,
    submenus: [
      { title: "Attendance Reports", href: "/student/reports", icon: FileSpreadsheet },
    ],
  },
];

export default function StudentLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const pathname = usePathname();
  const { user, logout } = useAuth();
  const [sidebarOpen, setSidebarOpen] = useState(false);
  const [openCategory, setOpenCategory] = useState<string | null>(null);

  // Topbar dropdown states
  const [notifOpen, setNotifOpen] = useState(false);
  const [userMenuOpen, setUserMenuOpen] = useState(false);
  const [searchVal, setSearchVal] = useState("");
  const notifRef = useRef<HTMLDivElement>(null);
  const userMenuRef = useRef<HTMLDivElement>(null);

  // Close dropdowns when clicking outside
  useEffect(() => {
    function handleClickOutside(event: MouseEvent) {
      if (notifRef.current && !notifRef.current.contains(event.target as Node)) {
        setNotifOpen(false);
      }
      if (userMenuRef.current && !userMenuRef.current.contains(event.target as Node)) {
        setUserMenuOpen(false);
      }
    }
    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  // Determine active category and active submenu title
  let activeCategoryLabel = "";
  let activeSubmenuTitle = "";

  // 1. Exact match with submenu
  for (const item of studentNavigation) {
    if (item.submenus) {
      for (const sub of item.submenus) {
        if (pathname === sub.href) {
          activeCategoryLabel = item.label;
          activeSubmenuTitle = sub.title;
          break;
        }
      }
    }
    if (activeCategoryLabel) break;
  }

  // 2. Exact match with main navigation item
  if (!activeCategoryLabel) {
    for (const item of studentNavigation) {
      if (pathname === item.href) {
        activeCategoryLabel = item.label;
        break;
      }
    }
  }

  // 3. Fallback prefix match for nested routes
  if (!activeCategoryLabel) {
    let longestMatchLen = 0;
    for (const item of studentNavigation) {
      if (item.submenus) {
        for (const sub of item.submenus) {
          if (pathname.startsWith(sub.href + "/") && sub.href.length > longestMatchLen) {
            activeCategoryLabel = item.label;
            activeSubmenuTitle = sub.title;
            longestMatchLen = sub.href.length;
          }
        }
      }
      if (pathname.startsWith(item.href + "/") && item.href.length > longestMatchLen) {
        activeCategoryLabel = item.label;
        longestMatchLen = item.href.length;
      }
    }
  }

  // Automatically keep active category open on initial load and route changes
  useEffect(() => {
    if (activeCategoryLabel) {
      setOpenCategory(activeCategoryLabel);
    }
  }, [activeCategoryLabel, pathname]);

  // SINGLE ACCORDION TOGGLE:
  // When clicking one category, close previous category and open this one.
  // If clicked again, close it.
  const handleToggleCategory = (categoryLabel: string) => {
    setOpenCategory((prev) => (prev === categoryLabel ? null : categoryLabel));
  };

  const handleSearchSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (!searchVal.trim()) return;
    toast.info(`Searching for "${searchVal}" across attendance records...`);
  };

  return (
    <RouteGuard allowedRoles={["STUDENT", "SUPER_ADMIN"]}>
      <div className="min-h-screen flex bg-[#F8FAFC] text-slate-800 antialiased font-sans selection:bg-[#F4B400] selection:text-[#081A2E]">
        {/* Mobile Sidebar Backdrop */}
        {sidebarOpen && (
          <div
            onClick={() => setSidebarOpen(false)}
            className="fixed inset-0 bg-[#081A2E]/70 z-40 lg:hidden backdrop-blur-2xs animate-in fade-in duration-200"
          />
        )}

        {/* ============================================================ */}
        {/* SIDEBAR: Deep Navy (#081A2E, 220px) matching Admin & Faculty */}
        {/* ============================================================ */}
        <aside
          style={{ ["--sidebar-active" as string]: "#F4B400" }}
          className={cn(
            "fixed inset-y-0 left-0 z-50 w-[220px] h-screen bg-[#081A2E] text-[#F5F7FA] flex flex-col justify-between transition-transform duration-200 ease-in-out lg:sticky lg:top-0 lg:h-screen lg:shrink-0 lg:translate-x-0 shadow-xl border-r border-[#0d2238]",
            sidebarOpen ? "translate-x-0" : "-translate-x-full"
          )}
        >
          {/* Top Brand with Golden Crest Banner */}
          <div className="shrink-0 p-3.5 border-b border-white/10 flex items-center justify-between">
            <Link href="/student/dashboard" className="flex items-center gap-2.5 group">
              <div className="w-9 h-9 rounded-full border border-[#D99A24] bg-[#05111F] flex items-center justify-center shrink-0 shadow-sm transition-transform group-hover:scale-105">
                <GraduationCap className="w-4.5 h-4.5 text-[#D99A24]" />
              </div>
              <div className="leading-tight">
                <span className="text-[9px] font-bold tracking-[0.16em] uppercase text-[#CBD5E1] block">
                  INSTITUTE OF
                </span>
                <span className="text-[11px] font-extrabold tracking-wide uppercase text-white block">
                  HOTEL MANAGEMENT
                </span>
                <span className="text-[9px] font-bold tracking-[0.2em] uppercase text-[#D99A24] block">
                  KOLKATA • STUDENT
                </span>
              </div>
            </Link>

            <button
              onClick={() => setSidebarOpen(false)}
              className="lg:hidden p-1 text-slate-400 hover:text-white rounded cursor-pointer"
              aria-label="Close sidebar"
            >
              <X className="w-5 h-5" />
            </button>
          </div>

          {/* Navigation Links Scrollable List */}
          <div className="flex-1 overflow-y-auto min-h-0 px-2 py-2 space-y-0.5 text-sm [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden no-scrollbar pb-3">
            {/* Student Portal Header Tag */}
            <div className="px-2.5 pt-1.5 pb-1 flex items-center justify-between">
              <span className="text-[10px] font-extrabold tracking-[0.2em] uppercase text-[#8FA3B8] font-sans">
                STUDENT CONSOLE
              </span>
              <span className="inline-flex items-center px-1.5 py-0.2 rounded text-[9px] font-bold bg-[#133252] text-[#D99A24] border border-[#1d4773]">
                NCHMCT
              </span>
            </div>

            {studentNavigation.map((item) => {
              const Icon = item.icon;
              const hasSubmenus = item.submenus && item.submenus.length > 0;
              const isOpen = hasSubmenus && openCategory === item.label;
              const isSelected = openCategory
                ? openCategory === item.label
                : item.label === activeCategoryLabel;

              return (
                <div key={item.label} className="space-y-0.5">
                  {hasSubmenus ? (
                    <button
                      type="button"
                      onClick={() => handleToggleCategory(item.label)}
                      className={cn(
                        "w-full flex items-center justify-between px-2.5 py-1.5 rounded-lg transition-all cursor-pointer group text-left",
                        isSelected
                          ? "bg-[#F4B400] text-[#081A2E] font-semibold shadow-xs"
                          : "text-[#F5F7FA] hover:bg-white/5 hover:text-white font-medium"
                      )}
                      title={isOpen ? `Collapse ${item.label}` : `Expand ${item.label}`}
                    >
                      <div className="flex items-center gap-2.5 flex-1 min-w-0">
                        <Icon
                          className={cn(
                            "w-4 h-4 shrink-0 transition-colors",
                            isSelected
                              ? "text-[#081A2E]"
                              : "text-[#E2E8F0] group-hover:text-white"
                          )}
                        />
                        <span className="truncate text-[12.5px] font-sans">{item.label}</span>
                      </div>

                      <ChevronDown
                        className={cn(
                          "w-3.5 h-3.5 shrink-0 transition-transform duration-200",
                          isSelected
                            ? "text-[#081A2E]"
                            : "text-[#8FA3B8] group-hover:text-white",
                          isOpen ? "rotate-0" : "-rotate-90"
                        )}
                      />
                    </button>
                  ) : (
                    <Link
                      href={item.href}
                      onClick={() => {
                        setOpenCategory(item.label);
                        setSidebarOpen(false);
                      }}
                      className={cn(
                        "w-full flex items-center gap-2.5 px-2.5 py-1.5 rounded-lg transition-all group",
                        isSelected
                          ? "bg-[#F4B400] text-[#081A2E] font-semibold shadow-xs"
                          : "text-[#F5F7FA] hover:bg-white/5 hover:text-white font-medium"
                      )}
                    >
                      <Icon
                        className={cn(
                          "w-4 h-4 shrink-0 transition-colors",
                          isSelected
                            ? "text-[#081A2E]"
                            : "text-[#E2E8F0] group-hover:text-white"
                        )}
                      />
                      <span className="truncate text-[12.5px] font-sans">{item.label}</span>
                    </Link>
                  )}

                  {/* Collapsible Submenus List */}
                  {hasSubmenus && isOpen && (
                    <div className="pl-2 pr-0.5 py-0.5 space-y-0.5 ml-2.5 my-0.5 font-sans border-l border-white/10 animate-in fade-in slide-in-from-top-1 duration-150">
                      {item.submenus?.map((sub) => {
                        const isSubActive =
                          pathname === sub.href || pathname.startsWith(sub.href + "/");
                        const SubIcon = sub.icon;
                        return (
                          <Link
                            key={sub.title}
                            href={sub.href}
                            onClick={() => setSidebarOpen(false)}
                            className={cn(
                              "flex items-center gap-2 px-2.5 py-1.5 rounded-[6px] text-xs transition-colors truncate group",
                              isSubActive
                                ? "bg-[#17385A] text-white font-semibold shadow-xs"
                                : "text-[#8FA3B8] font-medium hover:text-[#F5F7FA] hover:bg-white/5"
                            )}
                          >
                            {SubIcon && (
                              <SubIcon
                                className={cn(
                                  "w-3.5 h-3.5 shrink-0 transition-colors",
                                  isSubActive
                                    ? "text-[#D99A24]"
                                    : "text-[#8FA3B8] group-hover:text-[#F5F7FA]"
                                )}
                              />
                            )}
                            <span className="truncate">{sub.title}</span>
                          </Link>
                        );
                      })}
                    </div>
                  )}
                </div>
              );
            })}
          </div>

          {/* ============================================================ */}
          {/* BOTTOM SIDEBAR IHM ARCHITECTURAL BRANDING FOOTER IN GOLD     */}
          {/* ============================================================ */}
          <SidebarBuildingFooter />
        </aside>

        {/* ============================================================ */}
        {/* MAIN BODY AREA & STICKY TOPBAR                                */}
        {/* ============================================================ */}
        <div className="flex-1 flex flex-col min-w-0">
          {/* Sticky White Header Bar */}
          <header className="h-14 bg-white border-b border-[#E5EAF0] px-4 md:px-6 flex items-center justify-between shrink-0 sticky top-0 z-20 shadow-2xs">
            <div className="flex items-center gap-3">
              <button
                type="button"
                onClick={() => setSidebarOpen(!sidebarOpen)}
                className="p-1.5 rounded-lg text-slate-500 hover:text-slate-800 hover:bg-slate-100 lg:hidden cursor-pointer"
                aria-label="Toggle Navigation Sidebar"
              >
                <Menu className="w-5 h-5" />
              </button>

              {/* Global search trigger */}
              <form onSubmit={handleSearchSubmit} className="relative hidden sm:block w-72">
                <Search className="w-3.5 h-3.5 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2" />
                <input
                  type="text"
                  placeholder="Search attendance, subjects, circulars..."
                  value={searchVal}
                  onChange={(e) => setSearchVal(e.target.value)}
                  className="w-full pl-8 pr-3 py-1.5 text-xs bg-[#F8FAFC] border border-[#E2E8F0] rounded-lg focus:outline-hidden focus:border-[#1769E8] focus:bg-white transition-colors"
                />
              </form>
            </div>

            {/* Right Status Controls */}
            <div className="flex items-center gap-3">
              {/* Session Status Pill */}
              <div className="hidden lg:flex items-center gap-2 px-2.5 py-1 rounded-md bg-[#F1F6FC] border border-[#D0E2FF] text-[11px] font-semibold text-[#1769E8]">
                <Clock className="w-3.5 h-3.5" />
                <span>Session 2026–27 • Autumn Term</span>
              </div>

              {/* Biometric Turnstile Sync Indicator */}
              <div className="hidden sm:flex items-center gap-1.5 px-2.5 py-1 rounded-md bg-emerald-50 border border-emerald-200 text-emerald-800 text-[11px] font-semibold">
                <span className="w-2 h-2 rounded-full bg-emerald-500 animate-pulse" />
                <span>Biometric Synced</span>
              </div>

              {/* Notifications Dropdown */}
              <div className="relative" ref={notifRef}>
                <button
                  type="button"
                  onClick={() => setNotifOpen(!notifOpen)}
                  className="relative p-1.5 rounded-lg text-slate-500 hover:text-[#071A4D] hover:bg-slate-100 transition-colors cursor-pointer"
                  aria-label="Notifications"
                >
                  <Bell className="w-4 h-4" />
                  <span className="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full" />
                </button>

                {notifOpen && (
                  <div className="absolute right-0 mt-2 w-80 bg-white rounded-xl shadow-lg border border-[#E2E8F0] py-2 z-50 animate-in fade-in zoom-in-95 duration-100">
                    <div className="px-4 py-2 border-b border-[#E2E8F0] flex items-center justify-between">
                      <span className="text-xs font-bold text-[#071A4D]">Student Circulars &amp; Alerts</span>
                      <span className="text-[10px] text-emerald-600 bg-emerald-50 px-1.5 py-0.5 rounded font-semibold">
                        2 New
                      </span>
                    </div>
                    <div className="divide-y divide-[#F1F5F9] max-h-60 overflow-y-auto text-xs">
                      <div className="p-3 hover:bg-slate-50 transition-colors">
                        <p className="font-semibold text-slate-800 text-[11px]">
                          Mid-Term Condonation Deadline
                        </p>
                        <p className="text-[10px] text-slate-500 mt-0.5">
                          Medical adjustment slips for September must be submitted before 25 October.
                        </p>
                      </div>
                      <div className="p-3 hover:bg-slate-50 transition-colors">
                        <p className="font-semibold text-slate-800 text-[11px]">
                          Kitchen Uniform Protocol Reminder
                        </p>
                        <p className="text-[10px] text-slate-500 mt-0.5">
                          Mandatory chef cap and apron compliance enforced at Kitchen B turnstiles.
                        </p>
                      </div>
                    </div>
                  </div>
                )}
              </div>

              {/* Student Profile Popover */}
              <div className="relative" ref={userMenuRef}>
                <button
                  type="button"
                  onClick={() => setUserMenuOpen(!userMenuOpen)}
                  className="flex items-center gap-2 p-1 pl-2 rounded-lg hover:bg-slate-100 transition-colors cursor-pointer"
                >
                  <div className="w-7 h-7 rounded-full bg-[#102A45] text-[#F4B400] flex items-center justify-center text-xs font-bold font-mono">
                    {user?.name ? user.name[0].toUpperCase() : "S"}
                  </div>
                  <div className="hidden sm:block text-left">
                    <span className="text-xs font-bold text-[#071A4D] block truncate max-w-[110px]">
                      {user?.name || "Student"}
                    </span>
                    <span className="text-[10px] text-[#64748B] block truncate max-w-[110px]">
                      {user?.nchmRollNumber || "Active Student"}
                    </span>
                  </div>
                  <ChevronDown className="w-3.5 h-3.5 text-slate-400" />
                </button>

                {userMenuOpen && (
                  <div className="absolute right-0 mt-2 w-56 bg-white rounded-xl shadow-lg border border-[#E2E8F0] py-1.5 z-50 animate-in fade-in zoom-in-95 duration-100">
                    <div className="px-3 py-2 border-b border-[#E2E8F0] mb-1">
                      <p className="text-xs font-bold text-[#071A4D]">{user?.name || "Student"}</p>
                      <p className="text-[10px] text-[#64748B]">{user?.email || "Student Portal"}</p>
                      {user?.nchmRollNumber && (
                        <p className="text-[10px] text-[#1769E8] font-mono mt-0.5">Roll: {user.nchmRollNumber}</p>
                      )}
                    </div>

                    <Link
                      href="/student/attendance/overall"
                      onClick={() => setUserMenuOpen(false)}
                      className="flex items-center gap-2 px-3 py-1.5 text-xs text-slate-700 hover:bg-slate-50 transition-colors"
                    >
                      <BarChart3 className="w-3.5 h-3.5 text-slate-500" />
                      <span>My Attendance Status</span>
                    </Link>

                    <Link
                      href="/student/adjustments/medical"
                      onClick={() => setUserMenuOpen(false)}
                      className="flex items-center gap-2 px-3 py-1.5 text-xs text-slate-700 hover:bg-slate-50 transition-colors"
                    >
                      <HeartPulse className="w-3.5 h-3.5 text-slate-500" />
                      <span>Medical Leave Slip</span>
                    </Link>

                    <button
                      type="button"
                      onClick={() => {
                        setUserMenuOpen(false);
                        logout();
                      }}
                      className="w-full flex items-center gap-2 px-3 py-1.5 text-xs text-rose-600 hover:bg-rose-50 transition-colors mt-1 border-t border-[#F1F5F9] cursor-pointer"
                    >
                      <LogOut className="w-3.5 h-3.5" />
                      <span>Sign Out</span>
                    </button>
                  </div>
                )}
              </div>
            </div>
          </header>

          {/* Main Content Workspace */}
          <main className="flex-1 overflow-y-auto p-3 sm:p-4 md:p-6 bg-[#F8FAFC]">
            {children}
          </main>
        </div>
      </div>
    </RouteGuard>
  );
}
