import {
  Breadcrumb,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbList,
  BreadcrumbPage,
  BreadcrumbSeparator,
} from '@mdxui/primitives/breadcrumb'
import { useNavigation } from '../context/navigation-context'
import type { BreadcrumbItemData } from '../types'

export interface AppBreadcrumbsProps {
  /** Custom breadcrumb items (overrides auto-generation) */
  items?: BreadcrumbItemData[]
  /** Base path to strip from the URL */
  basePath?: string
  /** Label mappings for path segments */
  labels?: Record<string, string>
  /** Whether to show home/dashboard as first item */
  showHome?: boolean
  /** Label for the home item */
  homeLabel?: string
  /** Path for the home item */
  homePath?: string
}

/**
 * Default labels for common path segments
 */
const defaultLabels: Record<string, string> = {
  admin: 'Dashboard',
  users: 'Users',
  products: 'Products',
  orders: 'Orders',
  categories: 'Categories',
  customers: 'Customers',
  settings: 'Settings',
  dashboards: 'Dashboards',
  create: 'Create',
  edit: 'Edit',
}

/**
 * Generates breadcrumb items from a URL path
 */
function generateBreadcrumbs(
  path: string,
  basePath: string,
  labels: Record<string, string>
): BreadcrumbItemData[] {
  // Remove base path and split into segments
  const normalizedPath = path.startsWith(basePath) ? path.slice(basePath.length) : path
  const segments = normalizedPath.split('/').filter(Boolean)

  const items: BreadcrumbItemData[] = []
  let currentPath = basePath

  segments.forEach((segment, index) => {
    currentPath = `${currentPath}/${segment}`
    const isLast = index === segments.length - 1

    // Get label from mappings or format the segment
    let label = labels[segment]
    if (!label) {
      // Check if it's a numeric ID
      if (/^\d+$/.test(segment)) {
        label = `#${segment}`
      } else {
        // Capitalize and replace dashes with spaces
        label = segment.charAt(0).toUpperCase() + segment.slice(1).replace(/-/g, ' ')
      }
    }

    items.push({
      label,
      href: isLast ? undefined : currentPath,
    })
  })

  return items
}

/**
 * AppBreadcrumbs renders a breadcrumb navigation based on the current path.
 * Can auto-generate breadcrumbs from URL or accept custom items.
 *
 * @example
 * ```tsx
 * // Auto-generate from current path
 * <AppBreadcrumbs basePath="/admin" />
 *
 * // With custom labels
 * <AppBreadcrumbs
 *   basePath="/admin"
 *   labels={{ 'api-keys': 'API Keys', team: 'Team Members' }}
 * />
 *
 * // Custom items
 * <AppBreadcrumbs
 *   items={[
 *     { label: 'Dashboard', href: '/admin' },
 *     { label: 'Users', href: '/admin/users' },
 *     { label: 'John Doe' },
 *   ]}
 * />
 * ```
 */
export function AppBreadcrumbs({
  items: customItems,
  basePath = '',
  labels: customLabels = {},
  showHome = true,
  homeLabel = 'Dashboard',
  homePath,
}: AppBreadcrumbsProps) {
  const { getCurrentPath, Link } = useNavigation()
  const currentPath = getCurrentPath()

  // Merge default labels with custom labels
  const labels = { ...defaultLabels, ...customLabels }

  // Use custom items or generate from path
  let items: BreadcrumbItemData[] = customItems ?? generateBreadcrumbs(currentPath, basePath, labels)

  // Add home item if needed and not already present
  if (showHome && items.length === 0) {
    items = [{ label: homeLabel }]
  } else if (showHome && items[0]?.label !== homeLabel) {
    const homeHref = items.length > 0 ? (homePath ?? (basePath || '/')) : undefined
    items = [{ label: homeLabel, href: homeHref }, ...items]
  }

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

  return (
    <Breadcrumb>
      <BreadcrumbList>
        {items.map((item, index) => (
          <BreadcrumbItem key={index}>
            {index > 0 && <BreadcrumbSeparator />}
            {item.href ? (
              <BreadcrumbLink asChild>
                <Link href={item.href}>{item.label}</Link>
              </BreadcrumbLink>
            ) : (
              <BreadcrumbPage>{item.label}</BreadcrumbPage>
            )}
          </BreadcrumbItem>
        ))}
      </BreadcrumbList>
    </Breadcrumb>
  )
}
