import React from 'react';
import { Link, useLocation } from 'react-router-dom';
import {
  Breadcrumb,
  BreadcrumbList,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbPage,
  BreadcrumbSeparator,
} from '@/components/ui/breadcrumb';
import { Package } from 'lucide-react';

interface BreadcrumbItem {
  label: string;
  href?: string;
}

interface AssetBreadcrumbProps {
  items?: BreadcrumbItem[];
}

const AssetBreadcrumb: React.FC<AssetBreadcrumbProps> = ({ items = [] }) => {
  const location = useLocation();

  // Generate breadcrumb items based on current path if not provided
  const generateBreadcrumbItems = (): BreadcrumbItem[] => {
    const pathSegments = location.pathname.split('/').filter(Boolean);
    const breadcrumbItems: BreadcrumbItem[] = [];

    // Always start with Asset Management
    breadcrumbItems.push({
      label: 'Asset Management',
      href: '/assets'
    });

    // Handle specific routes
    if (pathSegments.includes('assets')) {
      if (pathSegments.length === 1) {
        // /assets - just show Asset Management as current page
        breadcrumbItems[0].href = undefined; // Make it current page
      } else if (pathSegments.length === 2 && pathSegments[1]) {
        // /assets/:id - show Assets > Asset Details
        breadcrumbItems.push({
          label: 'Asset Details'
        });
      }
    } else if (pathSegments.includes('system-details')) {
      breadcrumbItems.push({
        label: 'System Details'
      });
    } else if (pathSegments.includes('asset-assignments')) {
      breadcrumbItems.push({
        label: 'Asset Assignments'
      });
    }

    return breadcrumbItems;
  };

  const breadcrumbItems = items.length > 0 ? items : generateBreadcrumbItems();

  return (
    <Breadcrumb className="mb-6">
      <BreadcrumbList>
        <BreadcrumbItem>
          <BreadcrumbLink asChild>
            <Link to="/" className="flex items-center gap-2">
              <Package className="h-4 w-4" />
              Dashboard
            </Link>
          </BreadcrumbLink>
        </BreadcrumbItem>
        <BreadcrumbSeparator />
{breadcrumbItems.reduce<React.ReactNode[]>((acc, item, index) => {
          const isLast = index === breadcrumbItems.length - 1;
          
          acc.push(
            <BreadcrumbItem key={`item-${index}`}>
              {item.href ? (
                <BreadcrumbLink asChild>
                  <Link to={item.href}>{item.label}</Link>
                </BreadcrumbLink>
              ) : (
                <BreadcrumbPage>{item.label}</BreadcrumbPage>
              )}
            </BreadcrumbItem>
          );
          
          if (!isLast) {
            acc.push(<BreadcrumbSeparator key={`sep-${index}`} />);
          }
          
          return acc;
        }, [])}
      </BreadcrumbList>
    </Breadcrumb>
  );
};

export default AssetBreadcrumb;