import type { ReactNode, ComponentProps } from 'react'
import { LayoutDashboard } from 'lucide-react'
import {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarHeader,
  SidebarMenu,
  SidebarMenuButton,
  SidebarMenuItem,
} from '@mdxui/primitives/sidebar'
import { useApp } from '../context/app-context'
import { useNavigation } from '../context/navigation-context'
import type { AppConfig } from '../types'

export interface AppSidebarProps extends ComponentProps<typeof Sidebar> {
  /** Override default header content */
  header?: ReactNode
  /** Override default navigation content */
  nav?: ReactNode
  /** Override default footer content */
  footer?: ReactNode
  /** Custom logo component */
  logo?: ReactNode
  /** App config override (defaults to context) */
  config?: AppConfig
}

/**
 * AppSidebar renders the main sidebar with app branding, navigation, and user menu.
 * Uses AppContext for configuration and navigation data.
 *
 * @example
 * ```tsx
 * <AppSidebar
 *   nav={<NavMain />}
 *   footer={<NavUser />}
 * />
 * ```
 */
export function AppSidebar({
  header,
  nav,
  footer,
  logo,
  config: configProp,
  variant = 'inset',
  ...props
}: AppSidebarProps) {
  const appContext = useApp()
  const { Link } = useNavigation()
  const config = configProp ?? appContext.config

  const defaultHeader = (
    <SidebarMenu>
      <SidebarMenuItem>
        <SidebarMenuButton size="lg" asChild>
          <Link href={config.basePath ?? '/'}>
            {logo ?? (
              <div className="bg-sidebar-primary text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg">
                <LayoutDashboard className="size-4" />
              </div>
            )}
            <div className="grid flex-1 text-left text-sm leading-tight">
              <span className="truncate font-medium">{config.name}</span>
              {config.description && (
                <span className="truncate text-xs">{config.description}</span>
              )}
            </div>
          </Link>
        </SidebarMenuButton>
      </SidebarMenuItem>
    </SidebarMenu>
  )

  return (
    <Sidebar variant={variant} {...props}>
      <SidebarHeader>{header ?? defaultHeader}</SidebarHeader>
      {nav && <SidebarContent>{nav}</SidebarContent>}
      {footer && <SidebarFooter>{footer}</SidebarFooter>}
    </Sidebar>
  )
}
