import { Link, router, usePage } from '@inertiajs/react';
import type { LucideIcon } from 'lucide-react';
import {
    LayoutGrid,
    Car,
    Layers,
    Network,
    History,
    FileText,
    ChevronsLeft,
    ChevronsRight,
    LogOut,
} from 'lucide-react';
import { Settings } from 'lucide-react';
import { useState } from 'react';
import {
    Select,
    SelectContent,
    SelectItem,
    SelectTrigger,
    SelectValue,
} from '@/components/ui/select';
import { useCatalogLocale, setCatalogLocale } from '@/hooks/use-catalog-locale';
import { useInitials } from '@/hooks/use-initials';
import { CATALOG_LOCALES } from '@/lib/catalog';
import { cn } from '@/lib/utils';

interface NavItem {
    label: string;
    icon: LucideIcon;
    href?: string;
    section?: string;
    adminOnly?: boolean;
}

/*
 * Catalog navigation (IA §2.1): Dashboard / Models / Variants / Structure
 * under "Catalog", Import Status under "System". The legacy mock items
 * (Inbox, Documents, Links, Admin, Campaign Portal, …) were removed with the
 * frontend phase — they have no data source in product_db (IA §11).
 *
 * ACL: Import Status is admin-only (`auth.can.manage_imports` — Laravel gate
 * `manage-imports`); the rest of the catalog is available to every
 * authenticated user.
 */
const NAV_ITEMS: (NavItem | { sectionTitle: string })[] = [
    { sectionTitle: 'Catalog' },
    { label: 'Dashboard', icon: LayoutGrid, href: '/' },
    { label: 'Models', icon: Car, href: '/models' },
    { label: 'Variants', icon: Layers, href: '/variants' },
    { label: 'Structure', icon: Network, href: '/structure' },
    { label: 'Disclaimers', icon: FileText, href: '/disclaimers' },
    { label: 'Pricelists', icon: FileText, href: '/pricelists' },
    { sectionTitle: 'System' },
    {
        label: 'Import Status',
        icon: History,
        href: '/imports',
        adminOnly: true,
    },
];

export function CatalogSidebar() {
    const [collapsed, setCollapsed] = useState(false);
    const { url, props } = usePage();
    const getInitials = useInitials();
    const catalogLocale = useCatalogLocale();

    const { user, can } = props.auth;

    const isActive = (href?: string) =>
        href === '/' ? url === '/' : Boolean(href && url.startsWith(href));

    const handleLogout = () => {
        router.post('/logout');
    };

    const navItems = NAV_ITEMS.filter(
        (item) =>
            !('adminOnly' in item) ||
            item.adminOnly === undefined ||
            can.manage_imports,
    );

    return (
        <aside
            className={cn(
                'z-50 flex shrink-0 flex-col bg-astara-purple text-white shadow-2xl transition-[width] duration-300 ease-in-out',
                collapsed ? 'w-20' : 'w-[260px]',
            )}
        >
            <div className="mb-2 flex items-center gap-4 p-6">
                <img
                    src="/astara-app.png"
                    width="36"
                    height="36"
                    alt="Astara"
                    className="rounded-lg object-contain"
                />
                {!collapsed && (
                    <span className="flex min-w-0 flex-col">
                        <span className="text-base leading-tight font-bold tracking-tight uppercase">
                            Astara
                        </span>
                        <span className="text-[9px] font-bold tracking-[0.28em] text-white/50 uppercase">
                            Product DB
                        </span>
                    </span>
                )}
            </div>

            <nav className="custom-scroll flex-1 space-y-0.5 overflow-x-visible overflow-y-auto pb-2">
                {navItems.map((item) =>
                    'sectionTitle' in item ? (
                        !collapsed && (
                            <div
                                key={item.sectionTitle}
                                className="px-7 pt-6 pb-1 text-[9px] font-bold tracking-widest text-white uppercase opacity-40"
                            >
                                {item.sectionTitle}
                            </div>
                        )
                    ) : (
                        <div
                            key={item.label}
                            title={collapsed ? item.label : undefined}
                        >
                            {item.href ? (
                                <Link
                                    href={item.href}
                                    prefetch="hover"
                                    className={cn(
                                        'flex items-center gap-3 rounded-lg px-3.5 py-2.5 text-[13px] no-underline transition-all duration-200 focus-visible:ring-2 focus-visible:ring-white/70 focus-visible:outline-none',
                                        collapsed && 'justify-center px-2.5',
                                        isActive(item.href)
                                            ? 'bg-white font-bold text-astara-purple shadow-[0_4px_12px_rgba(0,0,0,0.15)]'
                                            : 'text-white/60 hover:bg-white/5 hover:text-white',
                                    )}
                                    aria-current={
                                        isActive(item.href) ? 'page' : undefined
                                    }
                                >
                                    <item.icon
                                        size={18}
                                        strokeWidth={
                                            isActive(item.href) ? 2.5 : 2
                                        }
                                        className={cn(
                                            'shrink-0',
                                            isActive(item.href) &&
                                                'text-astara-orange',
                                        )}
                                    />
                                    {!collapsed && (
                                        <span className="whitespace-nowrap">
                                            {item.label}
                                        </span>
                                    )}
                                </Link>
                            ) : (
                                <button
                                    type="button"
                                    className={cn(
                                        'flex w-full cursor-pointer items-center gap-3 rounded-lg px-3.5 py-2.5 text-[13px] text-white/60 transition-all duration-200 hover:bg-white/5 hover:text-white',
                                        collapsed && 'justify-center px-2.5',
                                    )}
                                >
                                    <item.icon
                                        size={18}
                                        strokeWidth={2}
                                        className="shrink-0"
                                    />
                                    {!collapsed && (
                                        <span className="whitespace-nowrap">
                                            {item.label}
                                        </span>
                                    )}
                                </button>
                            )}
                        </div>
                    ),
                )}
            </nav>

            <div className="mt-auto border-t border-white/10 p-4">
                {!collapsed && (
                    <div className="mb-3">
                        <p className="mb-1.5 text-[9px] font-bold tracking-widest text-white/40 uppercase">
                            Content language
                        </p>
                        <Select
                            value={catalogLocale}
                            onValueChange={setCatalogLocale}
                        >
                            <SelectTrigger
                                size="sm"
                                className="w-full bg-white/10 text-[11px] text-white"
                            >
                                <SelectValue />
                            </SelectTrigger>
                            <SelectContent>
                                {CATALOG_LOCALES.map((code) => (
                                    <SelectItem
                                        key={code}
                                        value={code}
                                        className="text-xs"
                                    >
                                        {code === 'de'
                                            ? 'Deutsch'
                                            : code === 'fr'
                                              ? 'Français'
                                              : 'Italiano'}
                                    </SelectItem>
                                ))}
                            </SelectContent>
                        </Select>
                    </div>
                )}
                {!collapsed && (
                    <Link
                        href="/settings/profile"
                        className="mb-2 flex items-center gap-2 rounded-lg px-1 py-1 text-[10px] font-bold tracking-widest text-white/50 uppercase no-underline transition-colors hover:text-white focus-visible:ring-2 focus-visible:ring-white/70 focus-visible:outline-none"
                    >
                        <Settings size={13} />
                        Account settings
                    </Link>
                )}
                <div className="flex items-center gap-3">
                    <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-astara-orange text-xs font-bold text-white">
                        {getInitials(user.name)}
                    </div>
                    {!collapsed && (
                        <div className="min-w-0 flex-1">
                            <p className="truncate text-xs font-bold">
                                {user.name}
                            </p>
                            <p className="truncate text-[10px] text-white/50">
                                {user.email}
                            </p>
                        </div>
                    )}
                    <button
                        type="button"
                        onClick={handleLogout}
                        aria-label="Log out"
                        title="Log out"
                        className="flex h-8 w-8 shrink-0 cursor-pointer items-center justify-center rounded-lg text-white/60 transition-colors hover:bg-white/10 hover:text-white"
                    >
                        <LogOut size={14} />
                    </button>
                </div>
            </div>

            <div className="bg-black/10 p-4">
                <button
                    type="button"
                    onClick={() => setCollapsed((c) => !c)}
                    className="flex w-full cursor-pointer items-center gap-4 rounded-lg p-2 transition-colors hover:bg-white/5"
                >
                    {collapsed ? (
                        <ChevronsRight size={18} />
                    ) : (
                        <>
                            <ChevronsLeft size={18} />
                            <span className="text-[10px] font-bold uppercase opacity-60">
                                Collapse Menu
                            </span>
                        </>
                    )}
                </button>
            </div>
        </aside>
    );
}
