import { ChevronRight } from 'lucide-react'
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@mdxui/primitives/collapsible'
import {
  SidebarGroup,
  SidebarGroupLabel,
  SidebarMenu,
  SidebarMenuAction,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarMenuSub,
  SidebarMenuSubButton,
  SidebarMenuSubItem,
} from '@mdxui/primitives/sidebar'
import { useNavigation } from '../context/navigation-context'
import type { NavGroup, NavItem } from '../types'

export interface NavMainProps {
  /** Navigation groups to render */
  groups?: NavGroup[]
  /** Single group of items (shorthand when only one group needed) */
  items?: NavItem[]
  /** Label for single group */
  label?: string
  /** Current path for active state detection */
  currentPath?: string
}

/**
 * NavMain renders the main navigation in the sidebar.
 * Supports collapsible groups with nested items.
 *
 * @example
 * ```tsx
 * // Single group
 * <NavMain
 *   label="Platform"
 *   items={[
 *     { title: 'Dashboard', url: '/admin', icon: LayoutDashboard },
 *     {
 *       title: 'Settings',
 *       url: '/admin/settings',
 *       icon: Settings,
 *       items: [
 *         { title: 'General', url: '/admin/settings/general' },
 *         { title: 'Team', url: '/admin/settings/team' },
 *       ],
 *     },
 *   ]}
 * />
 *
 * // Multiple groups
 * <NavMain
 *   groups={[
 *     { label: 'Main', items: [...] },
 *     { label: 'Settings', items: [...] },
 *   ]}
 * />
 * ```
 */
export function NavMain({
  groups,
  items,
  label = 'Navigation',
  currentPath: currentPathProp,
}: NavMainProps) {
  const { getCurrentPath, Link } = useNavigation()
  const currentPath = currentPathProp ?? getCurrentPath()

  // Convert single items array to groups format
  const navGroups: NavGroup[] = groups ?? (items ? [{ label, items }] : [])

  if (navGroups.length === 0) {
    return null
  }

  return (
    <>
      {navGroups.map((group) => (
        <SidebarGroup key={group.label}>
          <SidebarGroupLabel>{group.label}</SidebarGroupLabel>
          <SidebarMenu>
            {group.items.map((item) => (
              <NavMainItem
                key={item.title}
                item={item}
                currentPath={currentPath}
                Link={Link}
              />
            ))}
          </SidebarMenu>
        </SidebarGroup>
      ))}
    </>
  )
}

interface NavMainItemProps {
  item: NavItem
  currentPath: string
  Link: React.ComponentType<{ href: string; children: React.ReactNode; className?: string }>
}

function NavMainItem({ item, currentPath, Link }: NavMainItemProps) {
  const isActive = currentPath === item.url || (item.url !== '/' && currentPath.startsWith(item.url))
  const hasSubItems = item.items && item.items.length > 0

  if (hasSubItems) {
    return (
      <Collapsible asChild defaultOpen={item.isActive || isActive}>
        <SidebarMenuItem>
          <SidebarMenuButton asChild tooltip={item.title}>
            <span>
              {item.icon && <item.icon />}
              <span>{item.title}</span>
            </span>
          </SidebarMenuButton>
          <CollapsibleTrigger asChild>
            <SidebarMenuAction className="data-[state=open]:rotate-90">
              <ChevronRight />
              <span className="sr-only">Toggle</span>
            </SidebarMenuAction>
          </CollapsibleTrigger>
          <CollapsibleContent>
            <SidebarMenuSub>
              {item.items!.map((subItem) => {
                const subIsActive =
                  currentPath === subItem.url ||
                  (subItem.url !== '/' && currentPath.startsWith(subItem.url))
                return (
                  <SidebarMenuSubItem key={subItem.title}>
                    <SidebarMenuSubButton asChild isActive={subIsActive}>
                      <Link href={subItem.url}>
                        <span>{subItem.title}</span>
                      </Link>
                    </SidebarMenuSubButton>
                  </SidebarMenuSubItem>
                )
              })}
            </SidebarMenuSub>
          </CollapsibleContent>
        </SidebarMenuItem>
      </Collapsible>
    )
  }

  return (
    <SidebarMenuItem>
      <SidebarMenuButton asChild tooltip={item.title} isActive={isActive}>
        <Link href={item.url}>
          {item.icon && <item.icon />}
          <span>{item.title}</span>
        </Link>
      </SidebarMenuButton>
    </SidebarMenuItem>
  )
}
