import { Link, router, usePage } from '@inertiajs/react';
import type { LucideIcon } from 'lucide-react';
import {
    BadgeCheck,
    Bell,
    ClipboardList,
    FileText,
    LayoutDashboard,
    Menu,
    PieChart,
    Settings,
    ShieldCheck,
    Upload,
    Users,
    Wallet,
} from 'lucide-react';
import { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import {
    Sheet,
    SheetContent,
    SheetHeader,
    SheetTitle,
} from '@/components/ui/sheet';
import { cn } from '@/lib/utils';

type AdminTab = {
    label: string;
    href: string;
    icon: LucideIcon;
    isActive: (path: string) => boolean;
};

const TABS: AdminTab[] = [
    {
        label: 'Panel',
        href: '/admin',
        icon: LayoutDashboard,
        isActive(path) {
            return path === '/admin' || path === '/admin/';
        },
    },
    {
        label: 'Usuarios',
        href: '/admin/usuarios',
        icon: Users,
        isActive(path) {
            return path.startsWith('/admin/usuarios');
        },
    },
    {
        label: 'Inversiones',
        href: '/admin/inversiones',
        icon: PieChart,
        isActive(path) {
            return path.startsWith('/admin/inversiones');
        },
    },
    {
        label: 'Import',
        href: '/admin/importacion-forex',
        icon: Upload,
        isActive(path) {
            return path.startsWith('/admin/importacion-forex');
        },
    },
    {
        label: 'Parámetros',
        href: '/admin/inversion',
        icon: Settings,
        isActive(path) {
            return path === '/admin/inversion';
        },
    },
    {
        label: 'Notificaciones',
        href: '/admin/notificaciones',
        icon: Bell,
        isActive(path) {
            return path.startsWith('/admin/notificaciones');
        },
    },
    {
        label: 'Legales',
        href: '/admin/documentos-legales',
        icon: FileText,
        isActive(path) {
            return path.startsWith('/admin/documentos-legales');
        },
    },
    {
        label: 'Verificación de identidad',
        href: '/admin/verificacion-kyc',
        icon: ShieldCheck,
        isActive(path) {
            return path.startsWith('/admin/verificacion-kyc');
        },
    },
    {
        label: 'Acreditaciones',
        href: '/admin/acreditacion-mensual',
        icon: BadgeCheck,
        isActive(path) {
            return path.startsWith('/admin/acreditacion-mensual');
        },
    },
    {
        label: 'Retiros',
        href: '/admin/retiros/solicitudes',
        icon: Wallet,
        isActive(path) {
            return path.startsWith('/admin/retiros');
        },
    },
    {
        label: 'Auditoría',
        href: '/admin/debug',
        icon: ClipboardList,
        isActive(path) {
            return path.startsWith('/admin/debug');
        },
    },
];

function currentPathSafe(url: string): string {
    return (url.split('?')[0] ?? '').split('#')[0] ?? '';
}

const FOREX_IMPORT_HREF = '/admin/importacion-forex';
const AUDIT_HREF = '/admin/debug';

function AdminNavLinks({
    tabs,
    path,
    variant,
    onNavigate,
}: {
    tabs: AdminTab[];
    path: string;
    variant: 'horizontal' | 'vertical';
    onNavigate?: () => void;
}) {
    return (
        <ul
            className={cn(
                variant === 'horizontal'
                    ? 'flex min-w-max gap-1 pb-px sm:gap-2'
                    : 'flex flex-col gap-0.5 p-2',
            )}
        >
            {tabs.map((tab) => {
                const active = tab.isActive(path);
                const Icon = tab.icon;

                return (
                    <li key={tab.href}>
                        <Link
                            className={cn(
                                'inline-flex items-center gap-2 font-medium transition-colors',
                                variant === 'horizontal'
                                    ? cn(
                                          'border-b-2 px-3 py-2.5 text-sm whitespace-nowrap sm:px-4',
                                          active
                                              ? 'border-primary text-foreground'
                                              : 'border-transparent text-muted-foreground hover:border-muted-foreground/40 hover:text-foreground',
                                      )
                                    : cn(
                                          'w-full rounded-lg px-3 py-2.5 text-sm',
                                          active
                                              ? 'bg-primary/15 text-foreground'
                                              : 'text-muted-foreground hover:bg-muted/60 hover:text-foreground',
                                      ),
                            )}
                            href={tab.href}
                            prefetch
                            preserveScroll
                            onClick={onNavigate}
                        >
                            <Icon
                                aria-hidden
                                className={cn(
                                    'size-4 shrink-0',
                                    active
                                        ? 'text-primary'
                                        : 'text-muted-foreground',
                                )}
                            />
                            {tab.label}
                        </Link>
                    </li>
                );
            })}
        </ul>
    );
}

export function AdminSubnav() {
    const { url, props } = usePage();
    const path = currentPathSafe(url);
    const showForexImport = props.adminNav?.forex_import_pending === true;
    const showAuditTab = props.adminNav?.adjustments_enabled === true;
    const [mobileOpen, setMobileOpen] = useState(false);

    const tabs = TABS.filter((tab) => {
        if (tab.href === FOREX_IMPORT_HREF) {
            return showForexImport;
        }
        if (tab.href === AUDIT_HREF) {
            return showAuditTab;
        }

        return true;
    });

    const activeTab = tabs.find((tab) => tab.isActive(path)) ?? tabs[0];

    useEffect(() => {
        return router.on('start', () => setMobileOpen(false));
    }, []);

    function closeMobileMenu() {
        setMobileOpen(false);
    }

    return (
        <nav
            aria-label="Secciones de administración"
            className="sticky top-0 z-10 -mx-2 border-b border-border bg-background/95 px-2 backdrop-blur supports-[backdrop-filter]:bg-background/80 md:-mx-0 md:px-0"
        >
            <div className="flex items-center gap-2 py-2 md:hidden">
                <Button
                    aria-expanded={mobileOpen}
                    aria-label={
                        mobileOpen
                            ? 'Cerrar menú de administración'
                            : 'Abrir menú de administración'
                    }
                    size="icon"
                    type="button"
                    variant="outline"
                    onClick={() => setMobileOpen((open) => !open)}
                >
                    <Menu className="size-5" aria-hidden />
                </Button>
                <span className="min-w-0 flex-1 truncate text-sm font-medium">
                    {activeTab?.label ?? 'Administración'}
                </span>
            </div>

            <Sheet open={mobileOpen} onOpenChange={setMobileOpen}>
                <SheetContent
                    className="w-[min(100vw-2rem,20rem)] p-0"
                    side="left"
                >
                    <SheetHeader className="border-b px-4 py-4 text-left">
                        <SheetTitle>Administración</SheetTitle>
                    </SheetHeader>
                    <AdminNavLinks
                        path={path}
                        tabs={tabs}
                        variant="vertical"
                        onNavigate={closeMobileMenu}
                    />
                </SheetContent>
            </Sheet>

            <div className="hidden overflow-x-auto md:block">
                <AdminNavLinks path={path} tabs={tabs} variant="horizontal" />
            </div>
        </nav>
    );
}
