"use client"

import { useEffect, useState } from "react"
import Link from "next/link"
import { usePathname } from "next/navigation"
import {
  AlertOctagon,
  AlertTriangle,
  ArrowLeftRight,
  Banknote,
  BadgeDollarSign,
  BookOpen,
  BookText,
  Boxes,
  Building2,
  CalendarCheck,
  CalendarClock,
  ChevronRight,
  ClipboardList,
  CreditCard,
  Factory,
  FileBarChart,
  FileText,
  HelpCircle,
  IdCard,
  Inbox,
  Landmark,
  LayoutGrid,
  LayoutTemplate,
  LineChart,
  ListTree,
  Menu,
  Package,
  PackageCheck,
  PackageSearch,
  PackageX,
  PlayCircle,
  PieChart,
  Receipt,
  ReceiptText,
  Ruler,
  Scale,
  ScrollText,
  Settings,
  ShieldCheck,
  ShoppingCart,
  SlidersHorizontal,
  Tag,
  Truck,
  Undo2,
  Users,
  Wallet,
  Warehouse,
  X,
  type LucideIcon,
} from "lucide-react"

import { cn } from "@/lib/utils"
import { useAuth } from "@/components/auth/AuthProvider"

// `code` must match the seeded NavItem/SubNavItem codes in ERPCore
// (Infra/Persistence/Configurations/NavItemConfiguration.cs / SubNavItemConfiguration.cs)
// so role-based filtering (via GET /auth/me's navCodes) can match entries here.
const navItems: {
  title: string
  code: string
  href: string
  /** Where clicking the row actually navigates, if different from `href`. `href` itself
   * stays the section prefix used to decide whether this row is "active". */
  landingHref?: string
  /** This item's own href has no page of its own (no landingHref either) — clicking the
   * row should only expand/collapse its children, never navigate. */
  expandOnly?: boolean
  icon: LucideIcon
  chevron?: boolean
  children?: { title: string; code: string; href: string; icon: LucideIcon }[]
}[] = [
  { title: "Dashboard", code: "dashboard", href: "/dashboard", icon: LayoutGrid },
  {
    title: "Products",
    code: "products",
    href: "/dashboard/products",
    icon: Package,
    chevron: true,
    children: [
      { title: "Item", code: "products.item", href: "/dashboard/products", icon: Boxes },
      { title: "Category", code: "products.category", href: "/dashboard/products/categories", icon: ListTree },
      { title: "Brand", code: "products.brand", href: "/dashboard/products/brands", icon: Tag },
      { title: "UOM", code: "products.uom", href: "/dashboard/products/uoms", icon: Ruler },
    ],
  },
  {
    title: "Procurement",
    code: "procurement",
    href: "/dashboard/procurement",
    // Clicking "Procurement" itself lands on Purchase Orders — the hub page underneath
    // has nothing on it (its card grid was removed once the sidebar grew these sub-items).
    landingHref: "/dashboard/procurement/purchase-orders",
    icon: ClipboardList,
    chevron: true,
    children: [
      { title: "Purchase Orders", code: "procurement.purchase-orders", href: "/dashboard/procurement/purchase-orders", icon: ShoppingCart },
      { title: "Purchase Returns", code: "procurement.purchase-returns", href: "/dashboard/procurement/purchase-returns", icon: PackageX },
      { title: "Vendors", code: "procurement.vendors", href: "/dashboard/vendors", icon: Truck },
      { title: "Requisitions", code: "procurement.requisitions", href: "/dashboard/procurement/requisitions", icon: ClipboardList },
      { title: "RFQs", code: "procurement.rfqs", href: "/dashboard/procurement/rfqs", icon: FileText },
    ],
  },
  {
    title: "Sales",
    code: "sales",
    href: "/dashboard/sales",
    landingHref: "/dashboard/sales/invoices",
    icon: ReceiptText,
    chevron: true,
    children: [
      { title: "Invoices", code: "sales.invoices", href: "/dashboard/sales/invoices", icon: FileText },
      { title: "Slips", code: "sales.slips", href: "/dashboard/sales/slips", icon: ShoppingCart },
      { title: "Bundle Sales", code: "sales.bundle-sales", href: "/dashboard/sales/bundles", icon: Boxes },
      { title: "Free Issues", code: "sales.free-issues", href: "/dashboard/sales/free-issues", icon: PackageX },
      // { title: "Reports", code: "sales.reports", href: "/dashboard/sales/reports", icon: FileBarChart },
    ],
  },
  { title: "Sales Returns", code: "sales-returns", href: "/dashboard/sales/sales-returns", icon: Undo2 },
  { title: "Receiving", code: "receiving", href: "/dashboard/receiving/grn", icon: PackageCheck, chevron: true },
  {
    title: "Stock",
    code: "stock",
    href: "/dashboard/stock",
    // Clicking "Stock" itself lands on Stock Ledger — the hub page underneath has nothing on
    // it (its card grid was removed once the sidebar grew these sub-items), same as Procurement.
    landingHref: "/dashboard/stock/ledger",
    icon: Warehouse,
    chevron: true,
    children: [
      { title: "Stock Ledger", code: "stock.ledger", href: "/dashboard/stock/ledger", icon: ScrollText },
      { title: "Stock Enquiry", code: "stock.enquiry", href: "/dashboard/stock/enquiry", icon: PackageSearch },
      { title: "Valuation", code: "stock.valuation", href: "/dashboard/stock/valuation", icon: BadgeDollarSign },
      { title: "Transfers", code: "stock.transfers", href: "/dashboard/stock/transfers", icon: ArrowLeftRight },
      { title: "Adjustments", code: "stock.adjustments", href: "/dashboard/stock/adjustments", icon: SlidersHorizontal },
      { title: "Counts", code: "stock.counts", href: "/dashboard/stock/counts", icon: ClipboardList },
      { title: "Reorder Alerts", code: "stock.reorder-alerts", href: "/dashboard/stock/reorder-alerts", icon: AlertTriangle },
      { title: "Wastage", code: "stock.wastage", href: "/dashboard/stock/wastage", icon: AlertOctagon },
    ],
  },
  { title: "Warehouses", code: "warehouses", href: "/dashboard/warehouse", icon: Building2, chevron: true },
  { title: "Orders", code: "orders", href: "/dashboard/orders", icon: ShoppingCart, chevron: true },
  {
    title: "Production",
    code: "production",
    href: "/dashboard/production",
    landingHref: "/dashboard/production/runs",
    icon: Factory,
    chevron: true,
    children: [
      { title: "Templates", code: "production.templates", href: "/dashboard/production/templates", icon: LayoutTemplate },
      { title: "Runs", code: "production.runs", href: "/dashboard/production/runs", icon: PlayCircle },
    ],
  },
  {
    title: "HRM",
    code: "hrm",
    href: "/dashboard/hrm",
    landingHref: "/dashboard/hrm/employees",
    icon: IdCard,
    chevron: true,
    children: [
      { title: "Employees", code: "hrm.employees", href: "/dashboard/hrm/employees", icon: Users },
      { title: "Attendance", code: "hrm.attendance", href: "/dashboard/hrm/attendance", icon: CalendarCheck },
      { title: "Leave", code: "hrm.leave", href: "/dashboard/hrm/leave", icon: CalendarClock },
      { title: "Payroll", code: "hrm.payroll", href: "/dashboard/hrm/payroll", icon: Banknote },
      // { title: "Reports", code: "hrm.reports", href: "/dashboard/hrm/reports", icon: FileBarChart },
      { title: "Settings", code: "hrm.settings", href: "/dashboard/hrm/settings", icon: SlidersHorizontal },
    ],
  },
  {
    title: "Ledgers",
    code: "ledgers",
    href: "/dashboard/ledgers",
    icon: Landmark,
    chevron: true,
    children: [
      { title: "Trial Balance", code: "ledgers.trial-balance", href: "/dashboard/ledgers/trial-balance", icon: Scale },
      { title: "Balance Sheet", code: "ledgers.balance-sheet", href: "/dashboard/ledgers/balance-sheet", icon: Landmark },
      { title: "General Ledger", code: "ledgers.general-ledger", href: "/dashboard/ledgers/general-ledger", icon: BookOpen },
      { title: "Profit & Loss", code: "ledgers.profit-and-loss", href: "/dashboard/ledgers/profit-and-loss", icon: LineChart },
      { title: "Cash Flow", code: "ledgers.cash-flow", href: "/dashboard/ledgers/cash-flow", icon: PieChart },
      { title: "Budget vs Actual", code: "ledgers.budget-vs-actual", href: "/dashboard/ledgers/budget-vs-actual", icon: BadgeDollarSign },
      { title: "Tax Report", code: "ledgers.tax-report", href: "/dashboard/ledgers/tax-report", icon: Receipt },
    ],
  },
  {
    title: "Accounts",
    code: "accounts",
    href: "/dashboard/accounts",
    icon: CreditCard,
    chevron: true,
    children: [
      { title: "Cash / Bank Accounts", code: "accounts.bank-accounts", href: "/dashboard/accounts/bank-accounts", icon: Wallet },
      { title: "Cheque Books", code: "accounts.cheque-books", href: "/dashboard/accounts/cheque-books", icon: BookText },
      { title: "Received Cheques", code: "accounts.received-cheques", href: "/dashboard/accounts/received-cheques", icon: Inbox },
    ],
  },
  {
    title: "Settings",
    code: "settings",
    href: "/dashboard/settings",
    expandOnly: true,
    icon: Settings,
    chevron: true,
    children: [
      { title: "Roles", code: "settings.roles", href: "/dashboard/settings/roles", icon: ShieldCheck },
      { title: "Users", code: "settings.users", href: "/dashboard/settings/users", icon: Users },
      { title: "Configuration", code: "products.configuration", href: "/dashboard/products/settings", icon: SlidersHorizontal },
    ],
  },
  { title: "Help", code: "help", href: "/dashboard/help", icon: HelpCircle },
]

function SidebarContent({
  items,
  collapsed,
  onCollapse,
  onClose,
  pathname,
  isMobile,
}: {
  items: typeof navItems
  collapsed: boolean
  onCollapse: () => void
  onClose?: () => void
  pathname: string
  isMobile: boolean
}) {
  const iconOnly = !isMobile && collapsed

  // Which parent menus are open. Starts with the parent that owns the active
  // route auto-expanded; user toggles are preserved across navigation.
  const [expanded, setExpanded] = useState<Record<string, boolean>>({})

  // Adjusted during render (not in an effect) each time pathname or the
  // available item set changes — `items` starts empty while auth/nav codes
  // are loading, so this also needs to re-run once the real list arrives.
  const autoExpandKey = `${pathname}::${items.map((i) => i.code).join(",")}`
  const [lastAutoExpandKey, setLastAutoExpandKey] = useState<string | null>(null)
  if (autoExpandKey !== lastAutoExpandKey) {
    setLastAutoExpandKey(autoExpandKey)
    const parent = items.find((i) => {
      if (!i.children?.length) return false
      if (i.children.some((c) => pathname === c.href || pathname.startsWith(`${c.href}/`))) return true
      // Landing on the parent's own hub page (e.g. /dashboard/settings itself,
      // not one of its children) should also reveal its sub-items.
      return pathname === i.href || pathname.startsWith(`${i.href}/`)
    })
    if (parent) {
      setExpanded((prev) => (prev[parent.code] ? prev : { ...prev, [parent.code]: true }))
    }
  }

  const toggleExpand = (code: string) =>
    setExpanded((prev) => ({ ...prev, [code]: !prev[code] }))

  return (
    <nav
      className={cn(
        "sidebar-surface flex h-full flex-col rounded-3xl bg-card p-3 shadow-sm ring-1 ring-foreground/10 transition-[width] duration-300 ease-in-out",
        !isMobile && (collapsed ? "w-20" : "w-64")
      )}
    >
      {/* Header */}
      <div
        className={cn(
          "mb-8 flex shrink-0 items-center gap-2.5 px-4 py-3",
          iconOnly ? "flex-col-reverse justify-center gap-3 px-0" : "justify-between"
        )}
      >
        <Link href="/dashboard" className="flex items-center gap-2.5" onClick={onClose}>
          <div className="flex size-8 shrink-0 items-center justify-center rounded-xl bg-primary/10">
            <svg viewBox="0 0 48 32" className="h-3.5 w-5 fill-primary">
              <path d="M24 16c-3-8-11-12-16-8s-3 14 6 14c5 0 8.5-2.5 10-6 1.5 3.5 5 6 10 6 9 0 11-10 6-14s-13 0-16 8Z" />
            </svg>
          </div>
          {!iconOnly && (
            <span className="text-lg font-bold tracking-tight text-foreground">Hexa ERP</span>
          )}
        </Link>

        <button
          type="button"
          onClick={isMobile ? onClose : onCollapse}
          aria-label={isMobile ? "Close menu" : collapsed ? "Expand sidebar" : "Minimize sidebar"}
          className="flex size-8 shrink-0 items-center justify-center rounded-xl text-muted-foreground hover:bg-muted hover:text-foreground"
        >
          {isMobile ? <X className="size-4" /> : <Menu className="size-4" />}
        </button>
      </div>

      {/* Nav items — scrolls internally when it overflows, without a visible
          scrollbar so the rounded panel stays clean. */}
      <ul className="flex min-h-0 flex-1 flex-col gap-0.5 overflow-y-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
        {items.map((item) => {
          const isActive =
            item.href === "/dashboard" ? pathname === item.href : pathname.startsWith(item.href)
          const hasChildren = !!item.children?.length && !iconOnly
          const isOpen = !!expanded[item.code]

          return (
            <li key={item.href}>
              <div
                className={cn(
                  "flex items-center rounded-2xl transition-colors",
                  isActive ? "bg-primary/10" : "hover:bg-muted"
                )}
              >
                <Link
                  href={item.landingHref ?? item.href}
                  title={iconOnly ? item.title : undefined}
                  onClick={() => {
                    onClose?.()
                    if (hasChildren) setExpanded((prev) => (prev[item.code] ? prev : { ...prev, [item.code]: true }))
                  }}
                  className={cn(
                    "flex flex-1 items-center gap-3 rounded-2xl px-4 py-1.5 text-base font-normal",
                    iconOnly && "justify-center px-0",
                    isActive ? "text-primary" : "text-foreground"
                  )}
                >
                  <item.icon
                    className={cn("size-3.5 shrink-0", isActive ? "text-primary" : "text-muted-foreground")}
                  />
                  {!iconOnly && (
                    <>
                      <span className="flex-1">{item.title}</span>
                      {item.chevron && !hasChildren && (
                        <ChevronRight
                          className={cn("size-4 shrink-0", isActive ? "text-primary/70" : "text-muted-foreground")}
                        />
                      )}
                    </>
                  )}
                </Link>

                {hasChildren && (
                  <button
                    type="button"
                    onClick={() => toggleExpand(item.code)}
                    aria-label={isOpen ? `Collapse ${item.title}` : `Expand ${item.title}`}
                    aria-expanded={isOpen}
                    className={cn(
                      "mr-2 flex size-7 shrink-0 items-center justify-center rounded-lg transition-colors hover:bg-foreground/10",
                      isActive ? "text-primary" : "text-muted-foreground"
                    )}
                  >
                    <ChevronRight
                      className={cn("size-4 transition-transform duration-300 ease-in-out", isOpen && "rotate-90")}
                    />
                  </button>
                )}
              </div>

              {hasChildren && (
                <div
                  className={cn(
                    "grid transition-all duration-300 ease-in-out",
                    isOpen ? "mt-1 grid-rows-[1fr] opacity-100" : "grid-rows-[0fr] opacity-0"
                  )}
                >
                  <div className="overflow-hidden">
                    <ul className="flex flex-col gap-0.5 pl-11">
                      {(() => {
                        // Longest-matching href wins so a shared prefix (e.g. "Item" and
                        // "Category" both live under /dashboard/products) doesn't light up
                        // more than one sub-item at once.
                        const activeChild = [...item.children!]
                          .filter((c) => pathname === c.href || pathname.startsWith(`${c.href}/`))
                          .sort((a, b) => b.href.length - a.href.length)[0]
                        return item.children!.map((child) => {
                          const childActive = child.href === activeChild?.href
                          return (
                            <li key={child.href}>
                              <Link
                                href={child.href}
                                onClick={onClose}
                                tabIndex={isOpen ? undefined : -1}
                                className={cn(
                                  "flex items-center gap-2.5 rounded-xl px-3 py-1 text-sm font-medium transition-colors",
                                  childActive
                                    ? "bg-primary/10 text-primary"
                                    : "text-muted-foreground hover:bg-muted hover:text-foreground"
                                )}
                              >
                                <child.icon
                                  className={cn("size-3 shrink-0", childActive ? "text-primary" : "text-muted-foreground")}
                                />
                                {child.title}
                              </Link>
                            </li>
                          )
                        })
                      })()}
                    </ul>
                  </div>
                </div>
              )}
            </li>
          )
        })}
      </ul>

      <div className="flex items-center justify-center pt-6">
        <div className="flex size-12 items-center justify-center rounded-2xl bg-muted ring-1 ring-foreground/10">
          <svg viewBox="0 0 48 32" className="h-4 w-6 fill-muted-foreground">
            <path d="M24 16c-3-8-11-12-16-8s-3 14 6 14c5 0 8.5-2.5 10-6 1.5 3.5 5 6 10 6 9 0 11-10 6-14s-13 0-16 8Z" />
          </svg>
        </div>
      </div>
    </nav>
  )
}

export function AppSidebar() {
  const pathname = usePathname() || "/"
  const [collapsed, setCollapsed] = useState(false)
  const [mobileOpen, setMobileOpen] = useState(false)
  const { navCodes, loading } = useAuth()

  // While /auth/me hasn't resolved yet, show nothing rather than briefly
  // flashing the full menu to a restricted role. Once resolved, a nav item
  // is visible if its own code is granted, or (for parents) if any child is.
  //
  // "procurement", "hrm", "sales", "production" and "stock" are exempted from that check
  // (frontend-only): no role is currently seeded with NAV:procurement/NAV:hrm/NAV:production
  // or their children server-side (stock's children specifically have no SubNavItem rows at
  // all yet), which would hide the whole section for everyone. Remove each bypass once roles
  // are granted the permission properly (Settings → Roles → Sidebar permissions) or a backend
  // seed grants it. This is also flagged in 02-SECURITY.md as the AR-09 sidebar-visibility
  // stopgap for HRM's salary/PII data — it hides HRM from the UI but doesn't enforce
  // anything server-side.
  const bypassCodes = new Set(["procurement", "sales", "sales-returns", "hrm", "production", "stock"])
  const visibleItems = loading
    ? []
    : navItems
        .filter((item) => bypassCodes.has(item.code) || navCodes.includes(item.code) || item.children?.some((c) => navCodes.includes(c.code)))
        .map((item) => ({
          ...item,
          children: bypassCodes.has(item.code) ? item.children : item.children?.filter((c) => navCodes.includes(c.code)),
        }))

  // Close mobile menu on route change
  useEffect(() => {
    const timeout = setTimeout(() => setMobileOpen(false), 0)
    return () => clearTimeout(timeout)
  }, [pathname])

  // Prevent body scroll when mobile menu is open
  useEffect(() => {
    document.body.style.overflow = mobileOpen ? "hidden" : ""
    return () => { document.body.style.overflow = "" }
  }, [mobileOpen])

  return (
    <>
      {/* ── Desktop sidebar ─────────────────────────────── */}
      <div className="my-3 hidden lg:my-4 lg:flex">
        <SidebarContent
          items={visibleItems}
          collapsed={collapsed}
          onCollapse={() => setCollapsed((v) => !v)}
          pathname={pathname}
          isMobile={false}
        />
      </div>

      {/* ── Mobile hamburger trigger ─────────────────────── */}
      <button
        type="button"
        onClick={() => setMobileOpen(true)}
        aria-label="Open menu"
        className="fixed top-8 left-5 z-40 flex size-8 items-center justify-center rounded-xl bg-card shadow-sm ring-1 ring-foreground/10 text-muted-foreground hover:bg-muted lg:hidden"
      >
        <Menu className="size-4" />
      </button>

      {/* ── Mobile overlay backdrop ──────────────────────── */}
      {mobileOpen && (
        <div
          className="fixed inset-0 z-40 bg-black/30 backdrop-blur-xs lg:hidden"
          onClick={() => setMobileOpen(false)}
          aria-hidden="true"
        />
      )}

      {/* ── Mobile drawer ────────────────────────────────── */}
      <div
        className={cn(
          "fixed inset-y-0 left-0 z-50 w-72 p-3 transition-transform duration-200 lg:hidden",
          mobileOpen ? "translate-x-0" : "-translate-x-full"
        )}
      >
        <SidebarContent
          items={visibleItems}
          collapsed={false}
          onCollapse={() => {}}
          onClose={() => setMobileOpen(false)}
          pathname={pathname}
          isMobile={true}
        />
      </div>
    </>
  )
}
