import { Outlet, Link, useNavigate, useLocation } from "react-router-dom";
import { SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar";
import {
  Sidebar, SidebarContent, SidebarGroup, SidebarGroupContent,
  SidebarGroupLabel, SidebarMenu, SidebarMenuButton, SidebarMenuItem,
  SidebarHeader, SidebarFooter, SidebarSeparator, useSidebar,
} from "@/components/ui/sidebar";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { NavLink } from "@/components/NavLink";
import { useAuth } from "@/contexts/AuthContext";
import NotificationDropdown from "@/components/NotificationDropdown";
import AiAssistantDrawer from "@/components/ai/AiAssistantDrawer";
import AiSearchBar from "@/components/ai/AiSearchBar";
import { usePermissions } from "@/hooks/usePermissions";
import { Button } from "@/components/ui/button";
import {
  DropdownMenu, DropdownMenuContent, DropdownMenuItem,
  DropdownMenuSeparator, DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import {
  Breadcrumb, BreadcrumbItem, BreadcrumbLink, BreadcrumbList,
  BreadcrumbPage, BreadcrumbSeparator,
} from "@/components/ui/breadcrumb";
import {
  GraduationCap, LogOut, User, Settings, LayoutDashboard, ClipboardList,
  FileText, Layers, BookOpen, Wand2, GitBranch, Users, BarChart3,
  Building2, History, CreditCard, Ticket, BookA, PenTool,
  Calendar, ChevronDown, HelpCircle, LucideIcon, Target, FolderOpen,
  CalendarDays, Landmark, UserPlus, ScrollText, Award,
  HelpCircle as FaqIcon, Bell, Workflow,
  CalendarOff, DollarSign, BookMarked, BarChartHorizontal, TrendingUp,
  Library, Activity, Warehouse, UserCog,
} from "lucide-react";
import React from "react";

// ============= Navigation Config =============
interface NavItem { title: string; url: string; icon: LucideIcon }

const overviewItems: NavItem[] = [
  { title: "Admin Dashboard", url: "/admin/dashboard", icon: LayoutDashboard },
  { title: "Platform Dashboard", url: "/admin/platform", icon: BarChart3 },
];

const lmsItems: NavItem[] = [
  { title: "Courses", url: "/admin/courses", icon: BookOpen },
  { title: "Students", url: "/admin/students", icon: Users },
  { title: "Teachers", url: "/admin/teachers", icon: GraduationCap },
  { title: "Batches", url: "/admin/batches", icon: Layers },
  { title: "Timetable", url: "/admin/timetable", icon: Calendar },
  { title: "Reports", url: "/admin/reports", icon: BarChart3 },
];

const academicItems: NavItem[] = [
  { title: "Assignments", url: "/admin/assignments", icon: ClipboardList },
  { title: "Exams List", url: "/admin/examsList", icon: FileText },
  { title: "Exam Structures", url: "/admin/exam-structures", icon: Layers },
  { title: "Rubrics", url: "/admin/rubrics", icon: BookOpen },
  { title: "Generation", url: "/admin/generation", icon: Wand2 },
  { title: "Approval Workflows", url: "/admin/approval-workflows", icon: GitBranch },
];

const adaptiveItems: NavItem[] = [
  { title: "Taxonomy", url: "/admin/taxonomy", icon: Target },
  { title: "Resources", url: "/admin/resources", icon: FolderOpen },
];

const institutionalItems: NavItem[] = [
  { title: "Academic Years", url: "/admin/academic-years", icon: CalendarDays },
  { title: "Departments", url: "/admin/departments", icon: Landmark },
  { title: "Admissions", url: "/admin/admissions", icon: UserPlus },
  { title: "Admission Register", url: "/admin/admission-register", icon: ScrollText },
  { title: "Exam Sessions", url: "/admin/exam-sessions", icon: FileText },
  { title: "Marksheets", url: "/admin/marksheets", icon: Award },
  { title: "Student Leave", url: "/admin/student-leave", icon: CalendarOff },
  { title: "Fees & Payments", url: "/admin/fees", icon: DollarSign },
  { title: "Lessons", url: "/admin/lessons", icon: BookMarked },
  { title: "Gradebook", url: "/admin/gradebook", icon: BarChartHorizontal },
  { title: "Student Progress", url: "/admin/student-progress", icon: TrendingUp },
  { title: "Library", url: "/admin/library", icon: Library },
  { title: "Activities", url: "/admin/activities", icon: Activity },
  { title: "Facilities", url: "/admin/facilities", icon: Warehouse },
];

const managementItems: NavItem[] = [
  { title: "Users", url: "/admin/users", icon: Users },
  { title: "Entities", url: "/admin/entities", icon: Building2 },
  { title: "Classrooms", url: "/admin/classrooms", icon: GraduationCap },
  { title: "User Roles", url: "/admin/user-roles", icon: UserCog },
  { title: "Roles & Permissions", url: "/admin/roles-permissions", icon: Settings },
  { title: "Authority Matrix", url: "/admin/authority-matrix", icon: Workflow },
];

const reportItems: NavItem[] = [
  { title: "Student Performance", url: "/admin/student-performance", icon: BarChart3 },
  { title: "Stats Corporate", url: "/admin/stats-corporate", icon: Building2 },
  { title: "Record", url: "/admin/record", icon: History },
];

const trainingItems: NavItem[] = [
  { title: "Vocabulary", url: "/admin/training/vocabulary", icon: BookA },
  { title: "Grammar", url: "/admin/training/grammar", icon: PenTool },
];

const configItems: NavItem[] = [
  { title: "FAQ Manager", url: "/admin/faq", icon: FaqIcon },
  { title: "Notification Rules", url: "/admin/notification-rules", icon: Bell },
  { title: "Approval Config", url: "/admin/approval-config", icon: Workflow },
];

const supportItems: NavItem[] = [
  { title: "Payment Record", url: "/admin/payment-record", icon: CreditCard },
  { title: "Tickets", url: "/admin/tickets", icon: Ticket },
  { title: "Settings", url: "/admin/settings-platform", icon: Settings },
];

// ============= Reusable sidebar group =============
function SidebarNavGroup({ label, items }: { label: string; items: NavItem[] }) {
  const { state } = useSidebar();
  const collapsed = state === "collapsed";

  return (
    <SidebarGroup>
      <SidebarGroupLabel>{label}</SidebarGroupLabel>
      <SidebarGroupContent>
        <SidebarMenu>
          {items.map((item) => (
            <SidebarMenuItem key={item.url}>
              <SidebarMenuButton asChild tooltip={item.title}>
                <NavLink
                  to={item.url}
                  end={item.url.endsWith("/dashboard") || item.url.endsWith("/platform")}
                  className="flex items-center gap-2 px-2 py-1.5 rounded-md text-sm text-sidebar-foreground hover:bg-sidebar-accent transition-colors"
                  activeClassName="bg-sidebar-accent text-sidebar-accent-foreground font-medium"
                >
                  <item.icon className="h-4 w-4 shrink-0" />
                  {!collapsed && <span>{item.title}</span>}
                </NavLink>
              </SidebarMenuButton>
            </SidebarMenuItem>
          ))}
        </SidebarMenu>
      </SidebarGroupContent>
    </SidebarGroup>
  );
}

// ============= Breadcrumbs =============
const routeLabels: Record<string, string> = {
  admin: "Admin", dashboard: "Dashboard", platform: "Platform", courses: "Courses",
  students: "Students", teachers: "Teachers", batches: "Batches", timetable: "Timetable",
  reports: "Reports", assignments: "Assignments", examsList: "Exams List",
  "exam-structures": "Exam Structures", rubrics: "Rubrics", generation: "Generation",
  "approval-workflows": "Approval Workflows", users: "Users", entities: "Entities",
  classrooms: "Classrooms", "student-performance": "Student Performance",
  "stats-corporate": "Stats Corporate", record: "Record", training: "Training",
  vocabulary: "Vocabulary", grammar: "Grammar", "payment-record": "Payment Record",
  tickets: "Tickets", "settings-platform": "Settings", settings: "Settings",
  profile: "Profile", exam: "Exam",
  "academic-years": "Academic Years", departments: "Departments",
  admissions: "Admissions", "admission-register": "Admission Register",
  "exam-sessions": "Exam Sessions", marksheets: "Marksheets",
  faq: "FAQ Manager", "notification-rules": "Notification Rules",
  "approval-config": "Approval Config",
  "student-leave": "Student Leave", fees: "Fees & Payments", lessons: "Lessons",
  gradebook: "Gradebook", "student-progress": "Student Progress",
  library: "Library", activities: "Activities", facilities: "Facilities",
};

function AppBreadcrumbs() {
  const location = useLocation();
  const segments = location.pathname.split("/").filter(Boolean);

  return (
    <Breadcrumb>
      <BreadcrumbList>
        <BreadcrumbItem>
          <BreadcrumbLink asChild><Link to="/admin/dashboard">Home</Link></BreadcrumbLink>
        </BreadcrumbItem>
        {segments.map((seg, i) => {
          const path = "/" + segments.slice(0, i + 1).join("/");
          const label = routeLabels[seg] || seg.charAt(0).toUpperCase() + seg.slice(1);
          const isLast = i === segments.length - 1;
          return (
            <React.Fragment key={path}>
              <BreadcrumbSeparator />
              <BreadcrumbItem>
                {isLast ? <BreadcrumbPage>{label}</BreadcrumbPage> : <BreadcrumbLink asChild><Link to={path}>{label}</Link></BreadcrumbLink>}
              </BreadcrumbItem>
            </React.Fragment>
          );
        })}
      </BreadcrumbList>
    </Breadcrumb>
  );
}

// ============= Main Layout =============
export default function AdminLmsLayout() {
  const { user, logout } = useAuth();
  const navigate = useNavigate();

  const initials = user?.name?.split(" ").map(w => w[0]).join("").slice(0, 2).toUpperCase() ?? "??";

  const handleLogout = async () => {
    await logout();
    navigate("/login");
  };

  return (
    <SidebarProvider>
      <div className="min-h-screen flex w-full">
        <AdminSidebar />
        <div className="flex-1 flex flex-col min-w-0">
          <header className="h-14 border-b bg-card flex items-center justify-between px-4 shrink-0">
            <div className="flex items-center gap-3">
              <SidebarTrigger />
              <AppBreadcrumbs />
            </div>
            <AiSearchBar />
            <div className="flex items-center gap-2">
              <NotificationDropdown />
              <Button variant="ghost" size="icon" onClick={() => navigate("/admin/tickets")} className="text-muted-foreground hover:text-foreground">
                <Ticket className="h-4 w-4" />
              </Button>
              <DropdownMenu>
                <DropdownMenuTrigger asChild>
                  <Button variant="ghost" size="icon" className="rounded-full">
                    <div className="h-8 w-8 rounded-full bg-primary flex items-center justify-center">
                      <span className="text-xs font-semibold text-primary-foreground">{initials}</span>
                    </div>
                  </Button>
                </DropdownMenuTrigger>
                <DropdownMenuContent align="end" className="w-48">
                  <div className="px-3 py-2">
                    <p className="text-sm font-medium">{user?.name ?? "User"}</p>
                    <p className="text-xs text-muted-foreground">{user?.email ?? ""}</p>
                  </div>
                  <DropdownMenuSeparator />
                  <DropdownMenuItem onClick={() => navigate("/admin/profile")}>
                    <User className="mr-2 h-4 w-4" /> Profile
                  </DropdownMenuItem>
                  <DropdownMenuItem onClick={() => navigate("/admin/settings-platform")}>
                    <Settings className="mr-2 h-4 w-4" /> Settings
                  </DropdownMenuItem>
                  <DropdownMenuSeparator />
                  <DropdownMenuItem onClick={handleLogout}>
                    <LogOut className="mr-2 h-4 w-4" /> Logout
                  </DropdownMenuItem>
                </DropdownMenuContent>
              </DropdownMenu>
            </div>
          </header>
          <main className="flex-1 overflow-auto p-6">
            <Outlet />
          </main>
        </div>
      </div>
      <AiAssistantDrawer />
      <Link
        to="/admin/tickets"
        className="fixed bottom-6 right-6 z-50 flex items-center gap-2 rounded-full bg-primary px-4 py-2.5 text-primary-foreground shadow-lg hover:opacity-90 transition-opacity"
      >
        <HelpCircle className="h-4 w-4" />
        <span className="text-sm font-medium">Need help?</span>
      </Link>
    </SidebarProvider>
  );
}

// ============= Admin Sidebar =============
function AdminSidebar() {
  const { state } = useSidebar();
  const collapsed = state === "collapsed";
  const { user } = useAuth();
  const { hasAnyPermission, isAdmin } = usePermissions();

  const showManagement = isAdmin || hasAnyPermission(["view_entities", "view_students", "view_teachers"]);
  const showReports = isAdmin || hasAnyPermission(["view_statistics", "view_student_performance", "view_entity_statistics"]);
  const showPayments = isAdmin || hasAnyPermission(["view_payment_record", "pay_entity"]);

  return (
    <Sidebar collapsible="icon">
      <SidebarHeader className="p-4">
        <div className="flex items-center gap-2">
          <img src="/logo.png" alt="EnCoach" className="h-8 w-8 rounded-lg shrink-0 object-contain" />
          {!collapsed && (
            <span className="text-lg font-bold tracking-tight text-sidebar-foreground">
              <span className="text-[hsl(42,40%,62%)]">En</span>
              <span>Coach</span>
            </span>
          )}
        </div>
      </SidebarHeader>
      <SidebarSeparator />
      <SidebarContent>
        <SidebarNavGroup label="Overview" items={overviewItems} />
        <SidebarNavGroup label="LMS" items={lmsItems} />
        <SidebarNavGroup label="Adaptive Learning" items={adaptiveItems} />
        <SidebarNavGroup label="Institutional" items={institutionalItems} />
        <SidebarNavGroup label="Academic" items={academicItems} />
        {showManagement && <SidebarNavGroup label="Management" items={managementItems} />}
        {showReports && <SidebarNavGroup label="Reports" items={reportItems} />}
        <SidebarNavGroup label="Configuration" items={configItems} />

        <SidebarGroup>
          <Collapsible defaultOpen className="group/collapsible">
            <SidebarGroupLabel asChild>
              <CollapsibleTrigger className="flex w-full items-center justify-between">
                Training
                {!collapsed && <ChevronDown className="h-4 w-4 transition-transform group-data-[state=open]/collapsible:rotate-180" />}
              </CollapsibleTrigger>
            </SidebarGroupLabel>
            <CollapsibleContent>
              <SidebarGroupContent>
                <SidebarMenu>
                  {trainingItems.map((item) => (
                    <SidebarMenuItem key={item.url}>
                      <SidebarMenuButton asChild tooltip={item.title}>
                        <NavLink
                          to={item.url}
                          className="flex items-center gap-2 px-2 py-1.5 rounded-md text-sm text-sidebar-foreground hover:bg-sidebar-accent transition-colors"
                          activeClassName="bg-sidebar-accent text-sidebar-accent-foreground font-medium"
                        >
                          <item.icon className="h-4 w-4 shrink-0" />
                          {!collapsed && <span>{item.title}</span>}
                        </NavLink>
                      </SidebarMenuButton>
                    </SidebarMenuItem>
                  ))}
                </SidebarMenu>
              </SidebarGroupContent>
            </CollapsibleContent>
          </Collapsible>
        </SidebarGroup>

        <SidebarNavGroup label="Support" items={showPayments ? supportItems : supportItems.filter(i => i.url !== "/admin/payment-record")} />
      </SidebarContent>
      <SidebarSeparator />
      <SidebarFooter className="p-3">
        <div className="flex items-center gap-2">
          <div className="h-8 w-8 rounded-full bg-primary/10 flex items-center justify-center shrink-0">
            <span className="text-xs font-semibold text-primary">{user?.name?.split(" ").map(w => w[0]).join("").slice(0, 2).toUpperCase() ?? "??"}</span>
          </div>
          {!collapsed && (
            <div className="flex flex-col min-w-0">
              <span className="text-sm font-medium truncate text-sidebar-foreground">{user?.name ?? "User"}</span>
              <span className="text-xs text-muted-foreground truncate">{user?.email ?? ""}</span>
            </div>
          )}
        </div>
      </SidebarFooter>
    </Sidebar>
  );
}
