import { Link, usePage, router } from '@inertiajs/react';
import type { ReactNode } from 'react';
import { PropsWithChildren, useState } from 'react';
import { LayoutDashboard, ShoppingCart, Truck, Users, BarChart2, BookOpen, Bell, Settings, ChevronDown, ChevronRight, LogOut, Menu, X } from 'lucide-react';
import { cn } from '@/lib/utils';

type NavItem = { label: string; href?: string; icon: any; children?: NavItem[]; active?: string[] };

const nav: NavItem[] = [
    { label: 'Dashboard', href: '/dashboard', icon: LayoutDashboard, active: ['dashboard'] },
    { label: 'Purchase Orders', href: '/purchase-orders', icon: ShoppingCart, active: ['purchase-orders*'] },
    { label: 'Suppliers', href: '/suppliers', icon: Users, active: ['suppliers*'] },
    { label: 'Delivery Orders', href: '/delivery-orders', icon: Truck, active: ['delivery-orders*'] },
    { label: 'Customers', href: '/customers', icon: Users, active: ['customers*'] },
    { label: 'Catalogue', href: '/catalogue', icon: BookOpen, active: ['catalogue*'] },
    { label: 'Reminders', href: '/reminders', icon: Bell, active: ['reminders*'] },
    { label: 'Analytics', icon: BarChart2, children: [
        { label: 'Dashboard', href: '/analytics/dashboard', icon: BarChart2 },
        { label: 'Calendar', href: '/analytics/calendar', icon: BarChart2 },
        { label: 'Price Tracker', href: '/analytics/price-tracker', icon: BarChart2 },
        { label: 'Delivery Time', href: '/analytics/delivery-time', icon: BarChart2 },
    ]},
    { label: 'Settings', icon: Settings, children: [
        { label: 'Company', href: '/settings/company', icon: Settings },
        { label: 'Templates', href: '/settings/templates', icon: Settings },
        { label: 'Header Templates', href: '/settings/header-templates', icon: Settings },
        { label: 'Users', href: '/settings/users', icon: Settings },
    ]},
];

function NavGroup({ item, currentUrl }: { item: NavItem; currentUrl: string }) {
    const isChildActive = item.children?.some(c => c.href && currentUrl.startsWith(c.href));
    const [open, setOpen] = useState(isChildActive ?? false);
    const Icon = item.icon;
    if (item.href) {
        const active = currentUrl === item.href || (item.href !== '/dashboard' && currentUrl.startsWith(item.href));
        return (
            <Link href={item.href} className={cn('flex items-center gap-3 px-3 py-2 rounded-md text-sm transition-colors', active ? 'bg-sidebar-accent text-white font-medium' : 'text-sidebar-muted hover:text-white hover:bg-sidebar-accent/60')}>
                <Icon className="w-4 h-4 flex-shrink-0" />{item.label}
            </Link>
        );
    }
    return (
        <div>
            <button onClick={() => setOpen(o => !o)} className={cn('w-full flex items-center gap-3 px-3 py-2 rounded-md text-sm transition-colors', isChildActive ? 'text-white' : 'text-sidebar-muted hover:text-white hover:bg-sidebar-accent/60')}>
                <Icon className="w-4 h-4 flex-shrink-0" /><span className="flex-1 text-left">{item.label}</span>
                {open ? <ChevronDown className="w-3 h-3" /> : <ChevronRight className="w-3 h-3" />}
            </button>
            {open && <div className="ml-7 mt-1 space-y-0.5 border-l border-sidebar-border pl-3">
                {item.children?.map(c => <NavGroup key={c.label} item={c} currentUrl={currentUrl} />)}
            </div>}
        </div>
    );
}

export default function AuthenticatedLayout({ children, header }: PropsWithChildren<{ header?: string | ReactNode }>) {
    const { auth } = usePage<import("@/types").PageProps>().props;
    const currentUrl = window.location.pathname;
    const [mobileOpen, setMobileOpen] = useState(false);

    const Sidebar = () => (
        <div className="flex flex-col h-full bg-sidebar">
            <div className="h-16 flex items-center px-6 border-b border-sidebar-border flex-shrink-0">
                <Link href="/dashboard" className="font-bold text-white text-lg tracking-tight">ProcureFlow</Link>
            </div>
            <nav className="flex-1 overflow-y-auto p-3 space-y-0.5">
                {nav.map(item => <NavGroup key={item.label} item={item} currentUrl={currentUrl} />)}
            </nav>
            <div className="p-3 border-t border-sidebar-border">
                <div className="flex items-center gap-3 px-3 py-2">
                    <div className="w-7 h-7 rounded-full bg-orange-500 flex items-center justify-center text-white text-xs font-bold flex-shrink-0">
                        {auth.user.name[0]?.toUpperCase()}
                    </div>
                    <div className="flex-1 min-w-0">
                        <p className="text-white text-sm font-medium truncate">{auth.user.name}</p>
                        <p className="text-sidebar-muted text-xs truncate">{auth.user.email}</p>
                    </div>
                    <button onClick={() => router.post('/logout')} className="text-sidebar-muted hover:text-white transition-colors"><LogOut className="w-4 h-4" /></button>
                </div>
            </div>
        </div>
    );

    return (
        <div className="flex h-screen bg-background overflow-hidden">
            <div className="hidden md:flex w-64 flex-shrink-0 flex-col"><Sidebar /></div>
            {mobileOpen && <div className="fixed inset-0 z-50 flex md:hidden"><div className="w-64 flex-shrink-0 flex flex-col"><Sidebar /></div><div className="flex-1 bg-black/50" onClick={() => setMobileOpen(false)} /></div>}
            <div className="flex-1 flex flex-col overflow-hidden">
                <div className="h-14 md:hidden flex items-center px-4 border-b bg-sidebar text-white flex-shrink-0">
                    <button onClick={() => setMobileOpen(true)} className="mr-3"><Menu className="w-5 h-5" /></button>
                    <span className="font-bold">ProcureFlow</span>
                </div>
                {header && <div className="border-b bg-white px-6 py-4 flex-shrink-0"><h1 className="text-lg font-semibold text-foreground">{header}</h1></div>}
                <main className="flex-1 overflow-y-auto p-6">{children}</main>
            </div>
        </div>
    );
}
