import React, { useEffect, useMemo, useState } from 'react';
import Layout from '../../components/Layout';
import { api } from '../../lib/api';
import { useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
import { Boxes, Search, Archive, ArchiveRestore, Trash2, Edit3, FileDown, Settings as SettingsIcon, BarChart3 } from 'lucide-react';

const PAGE_SIZE = 50;

export default function PalettesList() {
    const navigate = useNavigate();
    const [items, setItems] = useState([]);
    const [total, setTotal] = useState(0);
    const [loading, setLoading] = useState(true);
    const [q, setQ] = useState('');
    const [archived, setArchived] = useState(0);
    const [offset, setOffset] = useState(0);

    const load = async () => {
        setLoading(true);
        try {
            const r = await api.get('/gp/palettes', { params: { q: q.trim() || undefined, archived, limit: PAGE_SIZE, offset } });
            setItems(r.data.items || []);
            setTotal(r.data.total || 0);
        } catch (err) {
            toast.error(err?.response?.data?.detail || 'Erreur chargement');
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => { load(); /* eslint-disable-next-line */ }, [archived, offset]);
    useEffect(() => { const t = setTimeout(() => { setOffset(0); load(); }, 300); return () => clearTimeout(t); /* eslint-disable-next-line */ }, [q]);

    const onArchive = async (e, p) => {
        e.stopPropagation();
        try {
            if (p.archived) await api.post(`/gp/palettes/${p.id}/unarchive`);
            else await api.post(`/gp/palettes/${p.id}/archive`);
            toast.success(p.archived ? 'Restaurée' : 'Archivée');
            load();
        } catch (err) { toast.error(err?.response?.data?.detail || 'Erreur'); }
    };

    const onDelete = async (e, p) => {
        e.stopPropagation();
        if (!window.confirm(`Supprimer définitivement cette palette ?`)) return;
        try {
            await api.delete(`/gp/palettes/${p.id}`);
            toast.success('Supprimée');
            load();
        } catch (err) { toast.error(err?.response?.data?.detail || 'Erreur'); }
    };

    const exportPdf = async () => {
        try {
            const r = await api.get('/gp/export-palettes-pdf', {
                params: { q: q.trim() || undefined, archived },
                responseType: 'blob',
            });
            const url = window.URL.createObjectURL(new Blob([r.data], { type: 'application/pdf' }));
            const a = document.createElement('a');
            a.href = url;
            a.download = `palettes_${archived ? 'archivees' : 'actives'}.pdf`;
            document.body.appendChild(a);
            a.click();
            a.remove();
            window.URL.revokeObjectURL(url);
        } catch (err) { toast.error('Erreur génération PDF'); }
    };

    return (
        <Layout>
            <div className="mb-6 flex items-start justify-between gap-4 flex-wrap">
                <div>
                    <p className="text-xs font-bold uppercase tracking-[0.2em] text-amber-600">Gestion Palettes</p>
                    <h1 className="mt-2 font-heading text-2xl sm:text-3xl lg:text-4xl font-black tracking-tight text-slate-900">Palettes Reliquat</h1>
                    <p className="mt-1.5 text-sm sm:text-base text-slate-600">Saisie automatique. Archivage auto chaque matin selon l'heure définie dans les paramètres.</p>
                </div>
                <div className="flex flex-wrap items-center gap-2">
                    <button
                        data-testid="palette-stats-btn"
                        onClick={() => navigate('/palettes/reliquat/stats')}
                        className="inline-flex items-center gap-2 rounded-md border border-slate-300 text-slate-700 bg-white px-5 h-11 text-sm font-heading font-bold hover:bg-slate-50 active:scale-[0.99] transition-all"
                    >
                        <BarChart3 className="h-4 w-4" /> Statistiques
                    </button>
                    <button
                        data-testid="palette-settings-btn"
                        onClick={() => navigate('/palettes/reliquat/settings')}
                        className="inline-flex items-center gap-2 rounded-md border border-slate-300 text-slate-700 bg-white px-5 h-11 text-sm font-heading font-bold hover:bg-slate-50 active:scale-[0.99] transition-all"
                    >
                        <SettingsIcon className="h-4 w-4" /> Paramètres
                    </button>
                    <button
                        data-testid="palette-export-pdf"
                        onClick={() => exportPdf()}
                        className="inline-flex items-center gap-2 rounded-md border border-amber-500 text-amber-700 bg-white px-5 h-11 text-sm font-heading font-bold hover:bg-amber-50 active:scale-[0.99] transition-all"
                    >
                        <FileDown className="h-4 w-4" /> Exporter PDF
                    </button>
                </div>
            </div>

            <div className="mb-4 flex items-center gap-3 flex-wrap">
                <div className="relative flex-1 max-w-md min-w-[200px]">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400 pointer-events-none" />
                    <input
                        data-testid="palette-search"
                        value={q}
                        onChange={(e) => setQ(e.target.value)}
                        placeholder="SSCC, produit, fournisseur, KLSTB…"
                        className="w-full h-11 rounded-md border border-slate-300 bg-white pl-10 pr-3 text-sm font-medium text-slate-900 focus:border-amber-500 focus:outline-none focus:ring-2 focus:ring-amber-500/20"
                    />
                </div>
                <div className="flex gap-2">
                    {[
                        { id: 0, label: 'Actives' },
                        { id: 1, label: 'Archivées' },
                    ].map((t) => (
                        <button
                            key={t.id}
                            data-testid={`palette-filter-${t.id}`}
                            onClick={() => { setOffset(0); setArchived(t.id); }}
                            className={`rounded-full border px-4 h-10 text-xs font-heading font-bold uppercase tracking-wider transition ${
                                archived === t.id
                                    ? 'bg-amber-500 text-white border-amber-500'
                                    : 'bg-white text-slate-700 border-slate-300 hover:border-amber-500 hover:text-amber-600'
                            }`}
                        >
                            {t.label}
                        </button>
                    ))}
                </div>
            </div>

            {loading ? (
                <div className="rounded-lg border border-slate-200 bg-white p-12 text-center text-slate-500">Chargement…</div>
            ) : items.length === 0 ? (
                <div className="rounded-lg border border-dashed border-slate-300 bg-white p-12 text-center">
                    <Boxes className="mx-auto h-10 w-10 text-slate-300" />
                    <p className="mt-3 font-heading font-bold text-slate-700">{archived ? 'Aucune palette archivée' : 'Aucune palette pour cette recherche'}</p>
                </div>
            ) : (
                <>
                    <p className="text-xs text-slate-500 mb-3">{total} palette{total > 1 ? 's' : ''}{q ? ` pour « ${q} »` : ''}</p>
                    <div className="overflow-hidden rounded-lg border border-slate-200 bg-white" data-testid="palettes-table">
                        <div className="hidden md:grid grid-cols-12 gap-3 px-4 py-2.5 bg-slate-50 border-b border-slate-200 text-[11px] font-bold uppercase tracking-wider text-slate-600">
                            <div className="col-span-1">Date</div>
                            <div className="col-span-3">Produit / Fournisseur</div>
                            <div className="col-span-2">SSCC</div>
                            <div className="col-span-2">Motif / Zone</div>
                            <div className="col-span-2">Créé par</div>
                            <div className="col-span-2 text-right">Actions</div>
                        </div>
                        {items.map((p) => (
                            <div
                                key={p.id}
                                data-testid={`palette-row-${p.id}`}
                                onClick={() => navigate(`/palettes/reliquat/${p.id}`)}
                                className="grid grid-cols-1 md:grid-cols-12 gap-1 md:gap-3 px-4 py-3 border-b border-slate-100 last:border-0 hover:bg-amber-50/40 cursor-pointer transition"
                            >
                                <div className="md:col-span-1 text-[11px] text-slate-500">{p.created_at ? new Date(p.created_at).toLocaleDateString('fr-FR', { day:'2-digit', month:'2-digit' }) : '—'}</div>
                                <div className="md:col-span-3 min-w-0">
                                    <p className="font-heading font-bold text-slate-900 truncate">{p.produit || p.fournisseur || '—'}</p>
                                    {p.fournisseur && p.produit && <p className="text-xs text-slate-500 truncate">{p.fournisseur}</p>}
                                    {p.klstb && <p className="text-[11px] text-slate-400 truncate">KLSTB: {p.klstb}</p>}
                                </div>
                                <div className="md:col-span-2 min-w-0">
                                    <p className="font-mono text-xs text-slate-700 truncate">{p.sscc || '—'}</p>
                                    {p.gtin && <p className="font-mono text-[11px] text-slate-400 truncate">GTIN {p.gtin}</p>}
                                </div>
                                <div className="md:col-span-2 flex flex-wrap gap-1 items-start">
                                    {p.motif && <span className="inline-flex items-center rounded-full bg-amber-100 text-amber-800 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider">{p.motif}</span>}
                                    {p.zone && <span className="inline-flex items-center rounded-full bg-slate-100 text-slate-700 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider">{p.zone}</span>}
                                    {p.nombre_palettes > 1 && <span className="inline-flex items-center rounded-full bg-blue-100 text-blue-800 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider">×{p.nombre_palettes}</span>}
                                </div>
                                <div className="md:col-span-2 text-xs text-slate-600 min-w-0">
                                    <p className="truncate">{p.created_by_name || '—'}</p>
                                    <p className="text-[11px] text-slate-400">{p.created_at ? new Date(p.created_at).toLocaleString('fr-FR', { day:'2-digit', month:'2-digit', year:'2-digit', hour:'2-digit', minute:'2-digit' }) : ''}</p>
                                </div>
                                <div className="md:col-span-2 flex md:justify-end gap-1.5">
                                    <button onClick={(e) => { e.stopPropagation(); navigate(`/palettes/reliquat/${p.id}`); }} data-testid={`palette-edit-${p.id}`} className="h-8 w-8 rounded-md hover:bg-amber-100 text-amber-700 flex items-center justify-center" title="Éditer">
                                        <Edit3 className="h-3.5 w-3.5" />
                                    </button>
                                    <button onClick={(e) => onArchive(e, p)} data-testid={`palette-archive-${p.id}`} className="h-8 w-8 rounded-md hover:bg-slate-100 text-slate-600 flex items-center justify-center" title={p.archived ? 'Restaurer' : 'Archiver'}>
                                        {p.archived ? <ArchiveRestore className="h-3.5 w-3.5" /> : <Archive className="h-3.5 w-3.5" />}
                                    </button>
                                    <button onClick={(e) => onDelete(e, p)} data-testid={`palette-delete-${p.id}`} className="h-8 w-8 rounded-md hover:bg-red-50 text-red-600 flex items-center justify-center" title="Supprimer">
                                        <Trash2 className="h-3.5 w-3.5" />
                                    </button>
                                </div>
                            </div>
                        ))}
                    </div>

                    {total > PAGE_SIZE && (
                        <div className="mt-5 flex items-center justify-between gap-3">
                            <p className="text-xs text-slate-500">Page {Math.floor(offset / PAGE_SIZE) + 1} / {Math.ceil(total / PAGE_SIZE)}</p>
                            <div className="flex gap-2">
                                <button disabled={offset === 0} onClick={() => setOffset(Math.max(0, offset - PAGE_SIZE))} className="rounded-md border border-slate-300 px-4 h-9 text-xs font-bold hover:bg-slate-50 disabled:opacity-40">Préc.</button>
                                <button disabled={offset + PAGE_SIZE >= total} onClick={() => setOffset(offset + PAGE_SIZE)} className="rounded-md border border-slate-300 px-4 h-9 text-xs font-bold hover:bg-slate-50 disabled:opacity-40">Suivant</button>
                            </div>
                        </div>
                    )}
                </>
            )}
        </Layout>
    );
}
