import Dropdown from '@/Components/Dropdown';
import ResponsiveNavLink from '@/Components/ResponsiveNavLink';
import { PageProps } from '@/types';
import { Link, usePage } from '@inertiajs/react';
import { PropsWithChildren, ReactNode, useState } from 'react';

type NavItem = {
    label: string;
    href?: string;
    active?: boolean;
    icon: ReactNode;
    badge?: string;
};

export default function Authenticated({
    header,
    children,
}: PropsWithChildren<{ header?: ReactNode }>) {
    const user = usePage<PageProps>().props.auth.user;
    const [showingNavigationDropdown, setShowingNavigationDropdown] =
        useState(false);

    const mainItems: NavItem[] = [
        {
            label: 'Tableau de bord',
            href: route('dashboard'),
            active: route().current('dashboard'),
            icon: <ChartIcon />,
        },
        {
            label: 'Entreprises',
            href: route('companies.index'),
            active: route().current('companies.index') || route().current('companies.show'),
            icon: <BuildingIcon />,
        },
        {
            label: 'Carte de France',
            href: route('geography.index'),
            active: route().current('geography.*'),
            icon: <MapIcon />,
        },
        {
            label: 'Contacts',
            href: route('contacts.index'),
            active: route().current('contacts.*'),
            icon: <ContactsIcon />,
        },
        {
            label: 'Opportunités',
            href: route('opportunities.index'),
            active: route().current('opportunities.*'),
            icon: <TargetIcon />,
        },
        {
            label: 'Relances',
            href: route('activities.follow-ups'),
            active: route().current('activities.follow-ups'),
            icon: <PhoneIcon />,
            badge: '3',
        },
        {
            label: 'Appels',
            href: route('activities.calls'),
            active: route().current('activities.calls'),
            icon: <PhoneIcon />,
        },
        {
            label: 'Tâches',
            href: route('activities.tasks'),
            active: route().current('activities.tasks'),
            icon: <TaskIcon />,
        },
        {
            label: 'Devis / Propositions',
            href: route('proposals.index'),
            active: route().current('proposals.*'),
            icon: <DocumentIcon />,
        },
        {
            label: 'Contrats',
            href: route('contracts.index'),
            active: route().current('contracts.*'),
            icon: <DocumentIcon />,
        },
        {
            label: 'Campagnes',
            href: route('campaigns.index'),
            active: route().current('campaigns.*'),
            icon: <CampaignIcon />,
        },
    ];
    const managementItems: NavItem[] = [
        {
            label: 'Import XLSX',
            href: route('companies.import.create'),
            active: route().current('companies.import.*'),
            icon: <ImportIcon />,
        },
        {
            label: 'Statistiques',
            href: route('statistics.index'),
            active: route().current('statistics.*'),
            icon: <ChartIcon />,
        },
        {
            label: 'Paramètres',
            href: route('settings.edit'),
            active: route().current('settings.*'),
            icon: <SettingsIcon />,
        },
        {
            label: 'Utilisateurs',
            href: route('users.index'),
            active: route().current('users.*'),
            icon: <ContactsIcon />,
        },
    ];

    return (
        <div className="min-h-screen bg-[#f4f7fb] text-slate-800">
            <header className="fixed inset-x-0 top-0 z-30 flex h-[70px] items-center justify-between bg-[#062853] px-4 text-white shadow-lg shadow-blue-950/10 lg:pl-7 lg:pr-7">
                <div className="flex items-center gap-4">
                    <button
                        type="button"
                        onClick={() =>
                            setShowingNavigationDropdown((visible) => !visible)
                        }
                        className="rounded-lg p-2 text-white/90 hover:bg-white/10 lg:hidden"
                        aria-label="Ouvrir la navigation"
                    >
                        <MenuIcon />
                    </button>
                    <Link href={route('dashboard')} className="flex items-center gap-3">
                        <span className="flex h-11 w-11 items-center justify-center rounded-full bg-gradient-to-br from-blue-500 to-emerald-400 shadow-inner">
                            <span className="h-6 w-6 rounded-full border-[5px] border-white/90 border-r-transparent" />
                        </span>
                        <span>
                            <span className="block text-lg font-bold tracking-wide">
                                EVIO CRM
                            </span>
                            <span className="block text-xs text-blue-100">
                                Pilotage commercial
                            </span>
                        </span>
                    </Link>
                </div>

                <div className="flex items-center gap-3 sm:gap-5">
                    <div className="hidden items-center gap-2 rounded-full border border-emerald-300/20 bg-emerald-500/10 px-3 py-1.5 text-sm text-emerald-100 md:flex">
                        <span className="h-2 w-2 rounded-full bg-emerald-400" />
                        CRM connecté
                    </div>
                    <span className="hidden h-8 w-px bg-white/15 sm:block" />
                    <Dropdown>
                        <Dropdown.Trigger>
                            <button
                                type="button"
                                aria-label="Menu utilisateur"
                                className="flex items-center gap-3 rounded-lg px-2 py-1.5 text-left hover:bg-white/10"
                            >
                                <span className="flex h-9 w-9 items-center justify-center rounded-full bg-blue-100 font-bold text-[#06336a]">
                                    {user?.name?.slice(0, 1).toUpperCase() ?? 'U'}
                                </span>
                                <span className="hidden sm:block">
                                    <span className="block text-sm font-semibold">
                                        {user?.name ?? 'Utilisateur'}
                                    </span>
                                    <span className="block text-xs text-blue-200">
                                        Commercial
                                    </span>
                                </span>
                                <ChevronIcon />
                            </button>
                        </Dropdown.Trigger>
                        <Dropdown.Content>
                            <Dropdown.Link href={route('profile.edit')}>
                                Profil
                            </Dropdown.Link>
                            <Dropdown.Link
                                href={route('logout')}
                                method="post"
                                as="button"
                            >
                                Déconnexion
                            </Dropdown.Link>
                        </Dropdown.Content>
                    </Dropdown>
                </div>
            </header>

            <aside className="fixed inset-y-0 left-0 z-20 hidden w-[232px] bg-[#062853] pt-[70px] text-blue-100 lg:block">
                <nav className="flex h-full flex-col justify-between overflow-y-auto px-3 py-6">
                    <div className="space-y-1">
                        {mainItems.map((item) => (
                            <DesktopNavItem key={item.label} item={item} />
                        ))}
                        <p className="px-4 pb-2 pt-7 text-[10px] font-semibold uppercase tracking-[0.2em] text-blue-300/60">
                            Gestion
                        </p>
                        {managementItems.map((item) => (
                            <DesktopNavItem key={item.label} item={item} />
                        ))}
                    </div>
                    <div className="space-y-1 border-t border-white/10 pt-4">
                        <Link
                            method="post"
                            as="button"
                            href={route('logout')}
                            className="flex w-full items-center gap-3 rounded-xl px-4 py-3 text-sm text-blue-100 transition hover:bg-white/10"
                        >
                            <LogoutIcon />
                            Déconnexion
                        </Link>
                    </div>
                </nav>
            </aside>

            {showingNavigationDropdown && (
                <nav className="fixed inset-x-0 top-[70px] z-20 border-b border-slate-200 bg-white p-3 shadow-xl lg:hidden">
                    {[...mainItems, ...managementItems]
                        .filter((item) => item.href)
                        .map((item) => (
                            <ResponsiveNavLink
                                key={item.label}
                                href={item.href as string}
                                active={item.active}
                            >
                                {item.label}
                            </ResponsiveNavLink>
                        ))}
                </nav>
            )}

            <div className="pt-[70px] lg:pl-[232px]">
                {header && (
                    <header className="border-b border-slate-200 bg-white">
                        <div className="mx-auto max-w-[1500px] px-4 py-5 sm:px-6 lg:px-7">
                            {header}
                        </div>
                    </header>
                )}
                <main>{children}</main>
            </div>
        </div>
    );
}

function DesktopNavItem({ item }: { item: NavItem }) {
    const classes = `flex items-center justify-between rounded-xl px-4 py-3 text-sm transition ${
        item.active
            ? 'bg-[#1763bd] font-semibold text-white shadow-md shadow-blue-950/20'
            : item.href
              ? 'text-blue-100 hover:bg-white/10 hover:text-white'
              : 'cursor-default text-blue-300/70'
    }`;
    const content = (
        <>
            <span className="flex items-center gap-3">
                {item.icon}
                {item.label}
            </span>
            {item.badge && (
                <span aria-hidden="true" className="rounded-full bg-rose-500 px-2 py-0.5 text-xs font-semibold text-white">
                    {item.badge}
                </span>
            )}
        </>
    );

    return item.href ? (
        <Link href={item.href} className={classes}>
            {content}
        </Link>
    ) : (
        <div className={classes}>{content}</div>
    );
}

function Icon({ children }: { children: ReactNode }) {
    return (
        <svg
            className="h-5 w-5 shrink-0"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
            strokeWidth="1.8"
        >
            {children}
        </svg>
    );
}

function ChartIcon() {
    return (
        <Icon>
            <path d="M4 19V9m6 10V5m6 14V11m4 8H2" />
        </Icon>
    );
}

function BuildingIcon() {
    return (
        <Icon>
            <path d="M4 21V5l8-3 8 3v16M8 8h2m4 0h2M8 12h2m4 0h2M8 16h2m4 0h2M10 21v-3h4v3" />
        </Icon>
    );
}

function ContactsIcon() {
    return (
        <Icon>
            <path d="M16 21v-2a4 4 0 0 0-8 0v2M12 13a4 4 0 1 0 0-8 4 4 0 0 0 0 8Zm7-1a3 3 0 0 1 2 3v2M18 5a3 3 0 0 1 0 6" />
        </Icon>
    );
}

function TargetIcon() {
    return (
        <Icon>
            <circle cx="12" cy="12" r="8" />
            <circle cx="12" cy="12" r="3" />
        </Icon>
    );
}

function PhoneIcon() {
    return (
        <Icon>
            <path d="M5 4h4l2 5-2.5 1.5a13 13 0 0 0 5 5L15 13l5 2v4c-8 1-16-7-15-15Z" />
        </Icon>
    );
}

function DocumentIcon() {
    return (
        <Icon>
            <path d="M7 3h7l4 4v14H7V3Zm7 0v5h5M10 12h5m-5 4h5" />
        </Icon>
    );
}

function MapIcon() {
    return (
        <Icon>
            <path d="M3 6.5 9 3l6 3.5L21 3v14.5L15 21l-6-3.5L3 21V6.5Zm6-3.5v14.5m6-11V21" />
        </Icon>
    );
}

function CampaignIcon() {
    return (
        <Icon>
            <path d="M4 13V9l12-5v14L4 13Zm12-5h2a3 3 0 0 1 0 6h-2M6 13l2 7h3l-2-6" />
        </Icon>
    );
}

function TaskIcon() {
    return (
        <Icon>
            <path d="M9 6h10M9 12h10M9 18h10M4 6l1 1 2-2m-3 7 1 1 2-2m-3 7 1 1 2-2" />
        </Icon>
    );
}

function ImportIcon() {
    return (
        <Icon>
            <path d="M12 3v12m0 0-4-4m4 4 4-4M4 18v3h16v-3" />
        </Icon>
    );
}

function SettingsIcon() {
    return (
        <Icon>
            <path d="M12 15.5a3.5 3.5 0 1 0 0-7 3.5 3.5 0 0 0 0 7Z" />
            <path d="M19 12a7.8 7.8 0 0 0-.1-1l2-1.5-2-3.4-2.4 1a7 7 0 0 0-1.7-1L14.5 3h-4l-.4 3.1a7 7 0 0 0-1.7 1l-2.4-1-2 3.4L6 11a7.8 7.8 0 0 0 0 2l-2 1.5 2 3.4 2.4-1a7 7 0 0 0 1.7 1l.4 3.1h4l.4-3.1a7 7 0 0 0 1.7-1l2.4 1 2-3.4-2-1.5c.1-.3.1-.7.1-1Z" />
        </Icon>
    );
}

function LogoutIcon() {
    return (
        <Icon>
            <path d="M10 17l5-5-5-5m5 5H3m10-9h7v18h-7" />
        </Icon>
    );
}

function MenuIcon() {
    return (
        <svg className="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeWidth="2" strokeLinecap="round" d="M3 6h18M3 12h18M3 18h18" />
        </svg>
    );
}

function ChevronIcon() {
    return (
        <svg
            className="hidden h-4 w-4 text-blue-200 sm:block"
            fill="none"
            stroke="currentColor"
            viewBox="0 0 24 24"
        >
            <path strokeWidth="2" strokeLinecap="round" d="m6 9 6 6 6-6" />
        </svg>
    );
}
