import { Fragment, type ReactNode } from 'react';
import { Link } from 'react-router-dom';
import { ChevronRight, Home } from 'lucide-react';
import { cn } from '@utils/cn';

export interface BreadcrumbItem {
  label: string;
  href?: string;
  icon?: ReactNode;
}

export interface BreadcrumbsProps {
  items: BreadcrumbItem[];
  separator?: ReactNode;
  showHome?: boolean;
  homeHref?: string;
  className?: string;
}

export function Breadcrumbs({
  items,
  separator,
  showHome = true,
  homeHref = '/dashboard',
  className,
}: BreadcrumbsProps) {
  const separatorElement = separator || (
    <ChevronRight className="h-4 w-4 text-gray-400" />
  );

  const allItems: BreadcrumbItem[] = showHome
    ? [{ label: 'Inicio', href: homeHref, icon: <Home className="h-4 w-4" /> }, ...items]
    : items;

  return (
    <nav aria-label="Breadcrumb" className={className}>
      <ol className="flex items-center space-x-2">
        {allItems.map((item, index) => {
          const isLast = index === allItems.length - 1;

          return (
            <Fragment key={index}>
              <li className="flex items-center">
                {item.href && !isLast ? (
                  <Link
                    to={item.href}
                    className="flex items-center gap-1.5 text-sm text-gray-500 hover:text-gray-700"
                  >
                    {item.icon}
                    <span>{item.label}</span>
                  </Link>
                ) : (
                  <span
                    className={cn(
                      'flex items-center gap-1.5 text-sm',
                      isLast ? 'font-medium text-gray-900' : 'text-gray-500'
                    )}
                    aria-current={isLast ? 'page' : undefined}
                  >
                    {item.icon}
                    <span>{item.label}</span>
                  </span>
                )}
              </li>
              {!isLast && (
                <li className="flex items-center" aria-hidden="true">
                  {separatorElement}
                </li>
              )}
            </Fragment>
          );
        })}
      </ol>
    </nav>
  );
}

// Hook for dynamic breadcrumbs based on route
import { useMatches } from 'react-router-dom';

export interface RouteHandle {
  breadcrumb?: string | ((params: Record<string, string>) => string);
}

export function useBreadcrumbs(): BreadcrumbItem[] {
  const matches = useMatches();

  // Build breadcrumbs from route matches
  return matches
    .filter((match) => {
      const handle = match.handle as RouteHandle | undefined;
      return handle?.breadcrumb;
    })
    .map((match) => {
      const handle = match.handle as RouteHandle;
      const label =
        typeof handle.breadcrumb === 'function'
          ? handle.breadcrumb(match.params as Record<string, string>)
          : handle.breadcrumb!;

      return {
        label,
        href: match.pathname,
      };
    });
}
