"use client"

import { CaretRight, type Icon } from '@/lib/icons'
import Link from "next/link"
import { usePathname } from "next/navigation"

import {
  Collapsible,
  CollapsibleContent,
  CollapsibleTrigger,
} from "@/components/ui/collapsible"
import {
  SidebarGroup,
  SidebarGroupLabel,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarMenuSub,
  SidebarMenuSubButton,
  SidebarMenuSubItem,
  useSidebar,
} from "@/components/ui/sidebar"

export function NavMain({
  label,
  items,
}: {
  label: string
  items: {
    title: string
    url: string
    icon?: Icon
    isActive?: boolean
    items?: {
      title: string
      url: string
      isActive?: boolean
      badge?: number
    }[]
  }[]
}) {
  const pathname = usePathname()
  const { isMobile, setOpenMobile } = useSidebar()
  const closeMobile = () => { if (isMobile) setOpenMobile(false) }

  // Returns the url of the best-matching subitem (longest prefix wins).
  // Handles detail pages: /customers/123 correctly activates the /customers subitem
  // without accidentally activating /customers/searches (a sibling).
  function bestSubMatch(subitems: { url: string }[]): string | null {
    let best: string | null = null
    for (const sub of subitems) {
      if (pathname === sub.url || pathname.startsWith(sub.url + "/")) {
        if (!best || sub.url.length > best.length) best = sub.url
      }
    }
    return best
  }

  const shouldBeOpen = (item: typeof items[0]) => {
    if (item.isActive) return true
    if (item.items) return bestSubMatch(item.items) !== null
    return false
  }

  return (
    <SidebarGroup>
      <SidebarGroupLabel>{label}</SidebarGroupLabel>
      <SidebarMenu>
        {items.map((item) => (
          <Collapsible
            key={item.title}
            asChild
            defaultOpen={shouldBeOpen(item)}
            className="group/collapsible"
          >
            <SidebarMenuItem>
              {item.items?.length ? (() => {
                const activeSubUrl = bestSubMatch(item.items)
                return (
                  <>
                    <CollapsibleTrigger asChild>
                      <SidebarMenuButton tooltip={item.title} className="cursor-pointer">
                        {item.icon && <item.icon />}
                        <span>{item.title}</span>
                        <CaretRight className="ml-auto transition-transform duration-200 group-data-[state=open]/collapsible:rotate-90" />
                      </SidebarMenuButton>
                    </CollapsibleTrigger>
                    <CollapsibleContent>
                      <SidebarMenuSub>
                        {item.items?.map((subItem) => (
                          <SidebarMenuSubItem key={subItem.title}>
                            <SidebarMenuSubButton asChild className="cursor-pointer" isActive={activeSubUrl === subItem.url}>
                              <Link
                                href={subItem.url}
                                onClick={closeMobile}
                                target={(item.title === "Auth Pages" || item.title === "Errors") ? "_blank" : undefined}
                                rel={(item.title === "Auth Pages" || item.title === "Errors") ? "noopener noreferrer" : undefined}
                              >
                                <span>{subItem.title}</span>
                                {subItem.badge != null && subItem.badge > 0 && (
                                  <span className="ml-auto flex h-4 min-w-4 items-center justify-center rounded-full bg-destructive px-1 text-[10px] font-bold text-destructive-foreground">
                                    {subItem.badge > 99 ? "99+" : subItem.badge}
                                  </span>
                                )}
                              </Link>
                            </SidebarMenuSubButton>
                          </SidebarMenuSubItem>
                        ))}
                      </SidebarMenuSub>
                    </CollapsibleContent>
                  </>
                )
              })() : (
                <SidebarMenuButton asChild tooltip={item.title} className="cursor-pointer" isActive={pathname === item.url || pathname.startsWith(item.url + "/")}>
                  <Link href={item.url} onClick={closeMobile}>
                    {item.icon && <item.icon />}
                    <span>{item.title}</span>
                  </Link>
                </SidebarMenuButton>
              )}
            </SidebarMenuItem>
          </Collapsible>
        ))}
      </SidebarMenu>
    </SidebarGroup>
  )
}
