import { Link, useLocation } from 'react-router-dom';
import { ChevronRight, Home } from 'lucide-react';
import { motion } from 'framer-motion';

interface BreadcrumbItem {
    label: string;
    path: string;
}

// Route mapping for Veridian Platform
const ROUTE_CONFIG: Record<string, { label: string; parent?: string }> = {
    '/': { label: 'Dashboard' },
    '/dashboard': { label: 'Operational Overview', parent: '/' },
    '/walkthrough': { label: 'Daily Walkthrough', parent: '/' },
    '/tasks': { label: 'Tasks', parent: '/' },
    '/tasks/templates': { label: 'SOP Templates', parent: '/tasks' },
    '/batches': { label: 'Batches', parent: '/' },
    '/rooms': { label: 'Rooms', parent: '/' },
    '/timeclock': { label: 'Time & Attendance', parent: '/' },
    '/supplies': { label: 'Inventory', parent: '/' },
    '/reports': { label: 'Advanced Analytics', parent: '/' },
    '/ipm': { label: 'IPM Dashboard', parent: '/' },
    '/touch-points': { label: 'Action Logs', parent: '/' },
    '/visitors': { label: 'Visitor Management', parent: '/' },
    '/compliance/audit': { label: 'Audit Trail', parent: '/' },
    '/compliance/documents': { label: 'Compliance Docs', parent: '/' },
    '/metrc': { label: 'METRC Sync', parent: '/' },
    '/environment': { label: 'Environmental Controls', parent: '/' },
    '/financial': { label: 'Financials', parent: '/' },
    '/insights': { label: 'AI Insights', parent: '/' },
    '/roles': { label: 'Access Control', parent: '/settings' },
    '/settings': { label: 'System Settings', parent: '/' },
    '/settings/walkthrough': { label: 'Walkthrough Config', parent: '/settings' },
};

const DYNAMIC_ROUTES: { pattern: RegExp; getLabel: (match: RegExpMatchArray) => string; parent: string }[] = [
    { pattern: /^\/batches\/(.+)$/, getLabel: () => 'Batch Details', parent: '/batches' },
    { pattern: /^\/rooms\/(.+)$/, getLabel: () => 'Room Details', parent: '/rooms' },
    { pattern: /^\/tasks\/(.+)$/, getLabel: () => 'Task Details', parent: '/tasks' },
];

function getBreadcrumbs(pathname: string): BreadcrumbItem[] {
    const crumbs: BreadcrumbItem[] = [];
    let currentPath = pathname;

    for (const route of DYNAMIC_ROUTES) {
        const match = pathname.match(route.pattern);
        if (match) {
            crumbs.unshift({ label: route.getLabel(match), path: pathname });
            currentPath = route.parent;
            break;
        }
    }

    while (currentPath && ROUTE_CONFIG[currentPath]) {
        const config = ROUTE_CONFIG[currentPath];
        if (!crumbs.find(c => c.path === currentPath)) {
            crumbs.unshift({ label: config.label, path: currentPath });
        }
        currentPath = config.parent || '';
    }

    return crumbs;
}

export function Breadcrumbs() {
    const location = useLocation();
    const crumbs = getBreadcrumbs(location.pathname);

    // Filter home
    if (location.pathname === '/' || location.pathname === '/dashboard' || crumbs.length <= 1) {
        return null;
    }

    return (
        <nav aria-label="Breadcrumb" className="mb-0">
            <ol className="flex items-center gap-1 text-[11px] font-bold uppercase tracking-widest text-[var(--color-text-tertiary)] transition-all">
                <li className="flex items-center">
                    <Link
                        to="/dashboard"
                        className="p-1 rounded-md hover:bg-slate-100 dark:hover:bg-slate-800 transition-colors"
                        aria-label="Home"
                    >
                        <Home size={12} />
                    </Link>
                </li>

                {crumbs.map((crumb, index) => {
                    const isLast = index === crumbs.length - 1;
                    if (crumb.path === '/' || crumb.path === '/dashboard') return null;

                    return (
                        <li key={crumb.path} className="flex items-center gap-1">
                            <ChevronRight size={10} className="opacity-40" />
                            {isLast ? (
                                <motion.span
                                    initial={{ opacity: 0, x: -4 }}
                                    animate={{ opacity: 1, x: 0 }}
                                    className="px-2 py-0.5 text-slate-600 dark:text-slate-300"
                                >
                                    {crumb.label}
                                </motion.span>
                            ) : (
                                <Link
                                    to={crumb.path}
                                    className="px-2 py-0.5 rounded-md hover:bg-slate-100 dark:hover:bg-slate-800 hover:text-slate-900 dark:hover:text-slate-100 transition-colors"
                                >
                                    {crumb.label}
                                </Link>
                            )}
                        </li>
                    );
                })}
            </ol>
        </nav>
    );
}

export function getPageTitle(pathname: string): string {
    for (const route of DYNAMIC_ROUTES) {
        const match = pathname.match(route.pattern);
        if (match) {
            return `${route.getLabel(match)} | Veridian`;
        }
    }

    const config = ROUTE_CONFIG[pathname];
    if (config) {
        return `${config.label} | Veridian`;
    }
    return 'Veridian - Cultivation Platform';
}
