import { Link, useRouterState } from "@tanstack/react-router";
import {
  Banknote,
  BookOpenCheck,
  Boxes,
  Building2,
  CalendarClock,
  CalendarDays,
  ChevronRight,
  ClipboardList,
  Coins,
  CreditCard,
  FileText,
  Gauge,
  History,
  IdCard,
  Landmark,
  LineChart,
  MessageSquare,
  PieChart,
  Receipt,
  Scale,
  Settings as SettingsIcon,
  ShoppingBag,
  Truck,
  ShieldCheck,
  UserRound,
  Users,
  Wallet,
  Wrench,
} from "lucide-react";
import {
  Sidebar,
  SidebarContent,
  SidebarGroup,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarHeader,
  SidebarFooter,

  SidebarMenu,
  SidebarMenuButton,
  useSidebar,
  SidebarMenuItem,
} from "@/components/ui/sidebar";
import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { useMyAccess } from "@/lib/access";
import { useBranding } from "@/hooks/useBranding";
import { Image as ImageIcon } from "lucide-react";

type NavItem = { to: string; label: string; icon: typeof Gauge };
type NavGroup = { label: string; icon: typeof Gauge; items: NavItem[]; alwaysOpen?: boolean };

/** ERP module tree: Home → operating cycles (Sales, Purchases) → core ledger → HR → BI → Admin. */
const groups: NavGroup[] = [
  {
    label: "Home",
    icon: Gauge,
    alwaysOpen: true,
    items: [{ to: "/dashboard", label: "Dashboard", icon: Gauge }],
  },
  {
    label: "Studio Operations",
    icon: Building2,
    items: [
      { to: "/bookings", label: "Bookings", icon: CalendarClock },
      { to: "/bookings/approvals", label: "Booking Approvals", icon: CalendarClock },
      { to: "/bookings/invoices", label: "Booking Invoices", icon: FileText },
      { to: "/bookings/payments", label: "Booking Payments", icon: CreditCard },
      { to: "/bookings/receipts", label: "Booking Receipts", icon: Receipt },
      { to: "/bookings/costs", label: "Booking Costs", icon: CalendarClock },

      { to: "/projects", label: "Projects & Jobs", icon: Landmark },
      { to: "/studios", label: "Studios", icon: Building2 },
      { to: "/rooms", label: "Rooms", icon: Boxes },
    ],
  },
  {
    label: "Sales & Receivables",
    icon: FileText,
    items: [
      { to: "/quotes", label: "Quotes", icon: FileText },
      { to: "/estimates", label: "Booking Estimates", icon: FileText },
      { to: "/invoices", label: "Invoices", icon: FileText },
      { to: "/invoices/approvals", label: "Invoice Approvals", icon: FileText },
      { to: "/invoices/portal", label: "Client Portal Invoices", icon: FileText },
      { to: "/payments", label: "Customer Payments", icon: CreditCard },
      { to: "/payments/apply", label: "Apply Payments", icon: CreditCard },
      { to: "/invoices/credit-notes", label: "Credit Notes", icon: FileText },
      { to: "/payments/refunds", label: "Refunds", icon: CreditCard },
      { to: "/customers", label: "Customers", icon: UserRound },
      { to: "/customers/balances", label: "Client Balances", icon: UserRound },
      { to: "/customers/portal", label: "Client Portal Access", icon: UserRound },
    ],
  },
  {
    label: "Purchases & Payables",
    icon: Truck,
    items: [
      { to: "/bills", label: "Vendor Bills", icon: ClipboardList },
      { to: "/expenses", label: "Expenses", icon: Receipt },
      { to: "/expenses/claims", label: "Expense Claims", icon: Receipt },
      { to: "/vendors", label: "Vendors", icon: Truck },
    ],
  },
  {
    label: "Catalog",
    icon: ShoppingBag,
    items: [
      { to: "/services", label: "Services", icon: Wrench },
      { to: "/services/costs", label: "Service Costs & Margin", icon: Coins },

      { to: "/products", label: "Products", icon: ShoppingBag },
    ],
  },
  {
    label: "Accounting",
    icon: BookOpenCheck,
    items: [
      { to: "/accounting", label: "Journals & Ledger", icon: BookOpenCheck },
      { to: "/accounting/trial-balance", label: "Trial Balance", icon: Scale },
      { to: "/accounting/verify-reset", label: "Balance Verification", icon: Scale },
      { to: "/accounting/opening-balances", label: "Opening Balances", icon: Coins },
      { to: "/cash-bank", label: "Cash & Bank", icon: Wallet },

      { to: "/cash-bank/balances", label: "Cash Balance Check", icon: Wallet },
      { to: "/cash-bank/register", label: "Bank Register", icon: Wallet },
      { to: "/cash-bank/reconcile", label: "Bank Reconciliation", icon: Wallet },
    ],
  },
  {
    label: "Owners & Equity",
    icon: Coins,
    items: [
      { to: "/owners", label: "Owners & Capital", icon: Coins },
      { to: "/profit-distribution", label: "Profit Distribution", icon: PieChart },
    ],
  },
  {
    label: "Human Resources",
    icon: Users,
    items: [
      { to: "/employees", label: "Employees", icon: IdCard },
      { to: "/attendance", label: "Attendance", icon: CalendarDays },
      { to: "/leave", label: "Leave & Holidays", icon: ClipboardList },
      { to: "/payroll", label: "Payroll", icon: Banknote },
      { to: "/payroll/batch", label: "Payroll Run (Batch)", icon: Banknote },
      { to: "/payroll/wages", label: "Salaries & Wages", icon: Banknote },
    ],
  },
  {
    label: "Reports & Analysis",
    icon: LineChart,
    items: [
      { to: "/reports", label: "Financial Reports", icon: LineChart },
      { to: "/reports/budget", label: "Budget vs Actual", icon: LineChart },
    ],
  },
  {
    label: "Administration",
    icon: SettingsIcon,
    items: [
      { to: "/settings", label: "Settings", icon: SettingsIcon },
      { to: "/settings/branding", label: "Logo & Branding", icon: ImageIcon },
      { to: "/users", label: "Users & Access", icon: ShieldCheck },
      { to: "/sms", label: "SMS Gateway", icon: MessageSquare },
      { to: "/audit-log", label: "Audit Log", icon: History },
    ],
  },
];


export function AppSidebar() {
  const pathname = useRouterState({ select: (s) => s.location.pathname });
  const { canView, loading } = useMyAccess();
  const { brandName, logoUrl, tagline, loading: brandingLoading } = useBranding();
  const { isMobile, setOpenMobile } = useSidebar();
  const closeOnMobile = () => {
    if (isMobile) setOpenMobile(false);
  };


  const visible = groups
    .map((group) => ({
      ...group,
      items: group.items.filter((item) => loading || canView(item.to.split("/")[1] ?? "")),
    }))
    .filter((group) => group.items.length > 0);

  return (
    <Sidebar>
      <SidebarHeader className="border-b border-sidebar-border px-4 py-4">
        <Link to="/dashboard" onClick={closeOnMobile} className="flex items-center gap-2 overflow-hidden">
          {logoUrl ? (
            <img
              src={logoUrl}
              alt={`${brandName} logo`}
              className="size-8 shrink-0 rounded-md bg-sidebar-accent object-contain"
            />
          ) : brandingLoading ? (
            <span className="size-8 shrink-0 animate-pulse rounded-md bg-sidebar-accent" />
          ) : (
            <span className="flex size-8 shrink-0 items-center justify-center rounded-md bg-sidebar-primary text-sidebar-primary-foreground text-sm font-bold">
              {brandName.slice(0, 1).toUpperCase()}
            </span>
          )}

          <span className="flex min-w-0 flex-col">
            <span className="truncate text-sm font-semibold">{brandName}</span>
            {tagline ? (
              <span className="truncate text-[11px] text-sidebar-foreground/60">{tagline}</span>
            ) : null}
          </span>
        </Link>
      </SidebarHeader>

      <SidebarContent className="gap-0">
        {visible.map((group) => {
          const groupActive = group.items.some((item) => pathname.startsWith(item.to));

          if (group.alwaysOpen) {
            return (
              <SidebarGroup key={group.label} className="py-2">
                <SidebarGroupContent>
                  <SidebarMenu>
                    {group.items.map((item) => (
                      <SidebarMenuItem key={item.to}>
                        <SidebarMenuButton asChild isActive={pathname.startsWith(item.to)}>
                          <Link to={item.to} onClick={closeOnMobile}>
                            <item.icon />
                            <span className="font-medium">{item.label}</span>
                          </Link>
                        </SidebarMenuButton>
                      </SidebarMenuItem>
                    ))}
                  </SidebarMenu>
                </SidebarGroupContent>
              </SidebarGroup>
            );
          }

          return (
            <Collapsible
              key={group.label}
              defaultOpen={groupActive}
              className="group/collapsible"
            >
              <SidebarGroup className="py-1">
                <SidebarGroupLabel asChild>
                  <CollapsibleTrigger className="flex w-full items-center gap-2 rounded-md px-2 text-[11px] font-semibold uppercase tracking-wide text-sidebar-foreground/60 hover:bg-sidebar-accent hover:text-sidebar-foreground">
                    <group.icon className="size-3.5 shrink-0" />
                    <span className="truncate">{group.label}</span>
                    <ChevronRight className="ml-auto size-3.5 shrink-0 transition-transform duration-200 group-data-[state=open]/collapsible:rotate-90" />
                  </CollapsibleTrigger>
                </SidebarGroupLabel>
                <CollapsibleContent>
                  <SidebarGroupContent>
                    <SidebarMenu>
                      {group.items.map((item) => (
                        <SidebarMenuItem key={item.to}>
                          <SidebarMenuButton asChild isActive={pathname.startsWith(item.to)}>
                            <Link to={item.to} onClick={closeOnMobile}>
                              <item.icon />
                              <span>{item.label}</span>
                            </Link>
                          </SidebarMenuButton>
                        </SidebarMenuItem>
                      ))}
                    </SidebarMenu>
                  </SidebarGroupContent>
                </CollapsibleContent>
              </SidebarGroup>
            </Collapsible>
          );
        })}
      </SidebarContent>


      <SidebarFooter className="border-t border-sidebar-border px-4 py-3">
        <div className="flex items-center gap-2 overflow-hidden">
          {logoUrl ? (
            <img
              src={logoUrl}
              alt={`${brandName} logo`}
              className="size-6 shrink-0 rounded object-contain"
            />
          ) : brandingLoading ? (
            <span className="size-6 shrink-0 animate-pulse rounded bg-sidebar-accent" />
          ) : (
            <span className="flex size-6 shrink-0 items-center justify-center rounded bg-sidebar-primary text-[10px] font-bold text-sidebar-primary-foreground">
              {brandName.slice(0, 1).toUpperCase()}
            </span>
          )}

          <div className="flex min-w-0 flex-col leading-tight">
            <span className="truncate text-[11px] font-medium text-sidebar-foreground/80">
              {brandName} · © {new Date().getFullYear()}
            </span>
            <span className="truncate text-[10px] text-sidebar-foreground/50">
              Developed by FOYSAL AHASAN
            </span>
          </div>
        </div>
      </SidebarFooter>
    </Sidebar>

  );
}
