import React from 'react';
import { NavLink, useNavigate, useLocation } from 'react-router-dom';
import { Home, FolderPlus, History, Settings, LogOut, User, Menu, KeyRound, Bell, Boxes, Archive, RotateCcw, Truck } from 'lucide-react';
import { useAuth } from '../context/AuthContext';
import { useSidebar } from '../context/SidebarContext';

const LOGO_URL = "/logo.png";

export default function Sidebar() {
    const { user, logout } = useAuth();
    const { open, setOpen, toggle } = useSidebar();
    const navigate = useNavigate();
    const location = useLocation();
    const isBureau = user?.role === 'bureau';
    const isPalettes = location.pathname.startsWith('/palettes');

    const closeOnMobile = () => {
        if (typeof window !== 'undefined' && window.innerWidth < 1024) {
            setOpen(false);
        }
    };

    const handleLogout = () => {
        logout();
        navigate('/login');
    };

    const items = [
        { to: '/', label: 'Accueil', icon: Home, testid: 'nav-home' },
    ];
    const truckItems = [
        { to: '/truck', label: 'Tableau de bord', icon: Truck, testid: 'nav-truck' },
        { to: '/new-folder', label: 'Nouveau dossier', icon: FolderPlus, testid: 'nav-new-folder' },
        { to: '/history', label: 'Historique', icon: History, testid: 'nav-history' },
    ];
    const palettesItems = [
        { to: '/palettes/reliquat', label: 'Palettes Reliquat', icon: Archive, testid: 'nav-reliquat' },
        { to: '/palettes/sav', label: 'Retours Fournisseurs', icon: RotateCcw, testid: 'nav-sav' },
    ];
    const accountItems = [
        { to: '/preferences', label: 'Mes notifications', icon: Bell, testid: 'nav-preferences' },
    ];
    if (isBureau) {
        accountItems.push({ to: '/settings', label: 'Paramètres', icon: Settings, testid: 'nav-settings' });
    }

    const linkCls = ({ isActive }, accent) =>
        `group flex items-center gap-3 rounded-md px-3 py-2.5 text-sm font-medium transition-all duration-200 ${
            isActive
                ? (accent === 'amber' ? 'bg-amber-500 text-white shadow-sm' : 'bg-stef text-white shadow-sm')
                : (accent === 'amber' ? 'text-slate-600 hover:bg-amber-50 hover:text-amber-700' : 'text-slate-600 hover:bg-slate-50 hover:text-stef')
        }`;

    const sectionTitle = (label, accent) => (
        <div className="mt-4 mb-1.5 px-3 flex items-center gap-2">
            <span className={`text-[10px] font-black uppercase tracking-[0.18em] ${accent === 'amber' ? 'text-amber-600' : 'text-stef'}`}>{label}</span>
            <div className={`flex-1 h-px ${accent === 'amber' ? 'bg-amber-200' : 'bg-stef/20'}`} />
        </div>
    );

    return (
        <>
            {/* Backdrop (mobile only) */}
            {open && (
                <div
                    className="fixed inset-0 z-30 bg-black/40 lg:hidden"
                    onClick={() => setOpen(false)}
                    data-testid="sidebar-backdrop"
                />
            )}

            <aside
                className={`fixed inset-y-0 left-0 z-40 flex w-64 flex-col border-r border-slate-200 bg-white transition-transform duration-300 ease-in-out ${
                    open ? 'translate-x-0' : '-translate-x-full'
                }`}
                data-testid="sidebar"
            >
                {/* Logo block — hamburger interne + logo + titre dynamique */}
                <div className="flex items-center gap-3 px-4 py-5 border-b border-slate-100">
                    <button
                        onClick={toggle}
                        className="h-9 w-9 shrink-0 rounded-md hover:bg-slate-100 flex items-center justify-center text-slate-600 transition"
                        data-testid="sidebar-close"
                        aria-label="Fermer le menu"
                    >
                        <Menu className="h-5 w-5" />
                    </button>
                    <NavLink
                        to="/"
                        end
                        onClick={closeOnMobile}
                        data-testid="sidebar-logo-home"
                        className="flex items-center gap-3 min-w-0 group flex-1"
                    >
                        <div className="flex h-11 w-11 shrink-0 items-center justify-center rounded-md bg-stef/5 ring-1 ring-stef/10 overflow-hidden group-hover:ring-stef/30 transition">
                            <img src={LOGO_URL} alt="STEF" className="h-full w-full object-contain" />
                        </div>
                        <div className="min-w-0">
                            {isPalettes ? (
                                <>
                                    <h1 className="font-heading text-base font-black tracking-tight text-slate-900 leading-none truncate">Gestion</h1>
                                    <h1 className="font-heading text-base font-black tracking-tight text-amber-600 leading-none mt-0.5 truncate">Palettes</h1>
                                </>
                            ) : (
                                <>
                                    <h1 className="font-heading text-base font-black tracking-tight text-slate-900 leading-none truncate group-hover:text-stef transition">Dossier</h1>
                                    <h1 className="font-heading text-base font-black tracking-tight text-stef leading-none mt-0.5 truncate">Camion</h1>
                                </>
                            )}
                        </div>
                    </NavLink>
                </div>

                {/* Nav */}
                <nav className="flex-1 px-3 py-4 overflow-y-auto">
                    {items.map(({ to, label, icon: Icon, testid }) => (
                        <NavLink key={to} to={to} end data-testid={testid} onClick={closeOnMobile} className={(s) => linkCls(s, 'stef')}>
                            <Icon className="h-4 w-4 shrink-0" />
                            <span className="truncate">{label}</span>
                        </NavLink>
                    ))}

                    {sectionTitle('Dossier Camion', 'stef')}
                    {truckItems.map(({ to, label, icon: Icon, testid }) => (
                        <NavLink key={to} to={to} data-testid={testid} onClick={closeOnMobile} className={(s) => linkCls(s, 'stef')}>
                            <Icon className="h-4 w-4 shrink-0" />
                            <span className="truncate">{label}</span>
                        </NavLink>
                    ))}

                    {isBureau && (
                        <>
                            {sectionTitle('Gestion Palettes', 'amber')}
                            {palettesItems.map(({ to, label, icon: Icon, testid }) => (
                                <NavLink key={to} to={to} data-testid={testid} onClick={closeOnMobile} className={(s) => linkCls(s, 'amber')}>
                                    <Icon className="h-4 w-4 shrink-0" />
                                    <span className="truncate">{label}</span>
                                </NavLink>
                            ))}
                        </>
                    )}

                    {sectionTitle('Mon compte', 'stef')}
                    {accountItems.map(({ to, label, icon: Icon, testid }) => (
                        <NavLink key={to} to={to} data-testid={testid} onClick={closeOnMobile} className={(s) => linkCls(s, 'stef')}>
                            <Icon className="h-4 w-4 shrink-0" />
                            <span className="truncate">{label}</span>
                        </NavLink>
                    ))}
                </nav>

                {/* User block */}
                <div className="border-t border-slate-100 p-4">
                    <div className="flex items-center gap-3 rounded-md bg-slate-50 p-3" data-testid="user-block">
                        <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-stef text-white">
                            <User className="h-4 w-4" />
                        </div>
                        <div className="flex-1 min-w-0">
                            <p className="font-heading text-sm font-bold text-slate-900 truncate">{user?.fullname || user?.username}</p>
                            <p className="text-xs uppercase tracking-wider text-slate-500">{isBureau ? 'Bureau' : 'Cariste'} · {user?.username}</p>
                        </div>
                    </div>
                    <button
                        onClick={() => { closeOnMobile(); navigate('/change-password'); }}
                        data-testid="sidebar-change-password"
                        className="mt-3 flex w-full items-center justify-center gap-2 rounded-md border border-slate-200 px-3 py-2 text-sm font-semibold text-slate-700 hover:bg-slate-50 transition-all"
                    >
                        <KeyRound className="h-4 w-4" />
                        Changer mon code
                    </button>
                    <button
                        onClick={handleLogout}
                        data-testid="logout-btn"
                        className="mt-2 flex w-full items-center justify-center gap-2 rounded-md border border-slate-200 px-3 py-2 text-sm font-semibold text-red-600 hover:bg-red-50 hover:border-red-200 transition-all"
                    >
                        <LogOut className="h-4 w-4" />
                        Déconnexion
                    </button>
                </div>
            </aside>
        </>
    );
}
