import React, { useEffect, useState } from 'react';
import Layout from '../../components/Layout';
import { api } from '../../lib/api';
import { useNavigate } from 'react-router-dom';
import { toast } from 'sonner';
import { Truck, Plus, Trash2, Edit3, FileText, Settings, X, Save, Archive, ArchiveRestore, BookUser } from 'lucide-react';

const PAGE_SIZE = 50;

function fmtDate(d) {
    if (!d) return '—';
    try {
        const [y, m, day] = String(d).slice(0, 10).split('-');
        return `${day}/${m}/${y}`;
    } catch { return String(d); }
}

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

    const load = async () => {
        setLoading(true);
        try {
            const r = await api.get('/gp/sav', { 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, b) => {
        e.stopPropagation();
        try {
            const r = await api.patch(`/gp/sav/${b.id}/archive`);
            toast.success(r?.data?.archived ? 'Bordereau archivé' : 'Bordereau restauré');
            load();
        } catch (err) { toast.error(err?.response?.data?.detail || 'Erreur'); }
    };

    const onDelete = async (e, b) => {
        e.stopPropagation();
        if (!window.confirm(`Supprimer ce bordereau (${b.totals?.lines || 0} ligne(s)) ?`)) return;
        try {
            await api.delete(`/gp/sav/${b.id}`);
            toast.success('Supprimé');
            load();
        } catch (err) { toast.error(err?.response?.data?.detail || 'Erreur'); }
    };

    const exportPdf = async (bid) => {
        try {
            const r = await api.get('/gp/export-sav-pdf', {
                params: { bid: bid || undefined, q: !bid ? (q.trim() || undefined) : undefined },
                responseType: 'blob',
            });
            const url = window.URL.createObjectURL(new Blob([r.data], { type: 'application/pdf' }));
            const a = document.createElement('a');
            a.href = url;
            a.download = bid ? `bordereau_${bid}.pdf` : 'bordereaux.pdf';
            document.body.appendChild(a);
            a.click();
            a.remove();
            window.URL.revokeObjectURL(url);
        } catch { 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">Retours Fournisseurs</h1>
                    <p className="mt-1.5 text-sm sm:text-base text-slate-600">Bordereaux de chargement (transporteur + destinataire + lignes fournisseur).</p>
                </div>
                <div className="flex gap-2 flex-wrap items-center">
                    <div className="flex gap-2 mr-1" data-testid="sav-filters">
                        {[
                            { id: 0, label: 'Actifs' },
                            { id: 1, label: 'Archivés' },
                        ].map((t) => (
                            <button
                                key={t.id}
                                data-testid={`sav-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>
                    <button data-testid="sav-clients-btn" onClick={() => navigate('/palettes/sav/clients')} className="inline-flex items-center gap-2 rounded-md border border-amber-300 bg-amber-50 text-amber-800 px-5 h-11 text-sm font-heading font-bold hover:bg-amber-100 active:scale-[0.99] transition-all">
                        <BookUser className="h-4 w-4" /> Clients
                    </button>
                    <button data-testid="sav-settings-btn" onClick={() => setShowSettings(true)} 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">
                        <Settings className="h-4 w-4" /> Paramètres
                    </button>
                    <button data-testid="sav-new-btn" onClick={() => navigate('/palettes/sav/new')} className="inline-flex items-center gap-2 rounded-md bg-amber-500 text-white px-5 h-11 text-sm font-heading font-bold hover:bg-amber-600 active:scale-[0.99] transition-all">
                        <Plus className="h-4 w-4" /> Nouveau bordereau
                    </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">
                    <Truck className="mx-auto h-10 w-10 text-slate-300" />
                    <p className="mt-3 font-heading font-bold text-slate-700">{archived ? 'Aucun bordereau archivé' : 'Aucun bordereau'}</p>
                    <p className="mt-1 text-xs text-slate-500">{archived ? 'Les bordereaux archivés apparaîtront ici.' : 'Crée ton premier bordereau de chargement.'}</p>
                </div>
            ) : (
                <>
                    <p className="text-xs text-slate-500 mb-3">{total} bordereau{total > 1 ? 'x' : ''}</p>
                    <div className="overflow-hidden rounded-lg border border-slate-200 bg-white" data-testid="sav-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-2">Livraison</div>
                            <div className="col-span-3">Transporteur</div>
                            <div className="col-span-2">Destinataire</div>
                            <div className="col-span-2">Totaux</div>
                            <div className="col-span-2 text-right">Actions</div>
                        </div>
                        {items.map((b) => (
                            <div key={b.id} data-testid={`sav-row-${b.id}`} onClick={() => navigate(`/palettes/sav/${b.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-xs text-slate-700 font-semibold">{fmtDate(b.date_bordereau)}</div>
                                <div className="md:col-span-2 text-xs text-slate-700">{b.livraison || '—'}</div>
                                <div className="md:col-span-3 min-w-0">
                                    <p className="text-sm text-slate-800 line-clamp-2 whitespace-pre-line">{b.transporteur || '—'}</p>
                                </div>
                                <div className="md:col-span-2 min-w-0">
                                    <p className="text-sm text-slate-800 line-clamp-2 whitespace-pre-line">{b.destinataire || '—'}</p>
                                </div>
                                <div className="md:col-span-2 flex flex-wrap gap-1 items-start">
                                    <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">{b.totals?.lines || 0} lig.</span>
                                    {b.totals?.nbre_pal > 0 && <span className="inline-flex items-center rounded-full bg-amber-200/60 text-amber-900 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider">{b.totals.nbre_pal} pal</span>}
                                    {b.totals?.nbre_colis > 0 && <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">{b.totals.nbre_colis} colis</span>}
                                </div>
                                <div className="md:col-span-2 flex md:justify-end gap-1.5">
                                    <button onClick={(e) => { e.stopPropagation(); exportPdf(b.id); }} data-testid={`sav-pdf-${b.id}`} className="h-8 w-8 rounded-md hover:bg-amber-100 text-amber-700 flex items-center justify-center" title="Exporter PDF">
                                        <FileText className="h-3.5 w-3.5" />
                                    </button>
                                    <button onClick={(e) => { e.stopPropagation(); navigate(`/palettes/sav/${b.id}`); }} data-testid={`sav-edit-${b.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, b)} data-testid={`sav-archive-${b.id}`} className="h-8 w-8 rounded-md hover:bg-slate-100 text-slate-600 flex items-center justify-center" title={b.archived ? 'Restaurer' : 'Archiver'}>
                                        {b.archived ? <ArchiveRestore className="h-3.5 w-3.5" /> : <Archive className="h-3.5 w-3.5" />}
                                    </button>
                                    <button onClick={(e) => onDelete(e, b)} data-testid={`sav-delete-${b.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>
                    )}
                </>
            )}
            {showSettings && <BordereauSettingsModal onClose={() => setShowSettings(false)} />}
        </Layout>
    );
}

function BordereauSettingsModal({ onClose }) {
    const [data, setData] = useState(null);
    const [saving, setSaving] = useState(false);

    useEffect(() => {
        api.get('/gp/bordereau-settings').then((r) => setData(r.data))
            .catch((e) => { toast.error(e?.response?.data?.detail || 'Erreur chargement'); onClose(); });
    }, [onClose]);

    const update = (k, v) => setData((d) => ({ ...d, [k]: v }));

    const save = async () => {
        setSaving(true);
        try {
            await api.put('/gp/bordereau-settings', data);
            toast.success('Paramètres mis à jour');
            onClose();
        } catch (e) { toast.error(e?.response?.data?.detail || 'Erreur'); }
        finally { setSaving(false); }
    };

    if (!data) return null;
    return (
        <div className="fixed inset-0 z-50 bg-black/40 flex items-start sm:items-center justify-center p-4 overflow-y-auto" data-testid="bs-modal">
            <div className="bg-white rounded-lg shadow-xl w-full max-w-2xl my-8">
                <div className="flex items-center justify-between px-5 py-3 border-b border-slate-200">
                    <h2 className="font-heading text-lg font-black text-slate-900">Paramètres du Bordereau</h2>
                    <button onClick={onClose} className="h-8 w-8 rounded-md hover:bg-slate-100 flex items-center justify-center text-slate-500" data-testid="bs-close">
                        <X className="h-5 w-5" />
                    </button>
                </div>
                <div className="px-5 py-4 space-y-4">
                    <div>
                        <label className="text-xs font-bold uppercase tracking-wider text-slate-700">Expéditeur (multi-lignes : nom, adresse, pays)</label>
                        <textarea data-testid="bs-expediteur" value={data.expediteur} onChange={(e) => update('expediteur', e.target.value)} rows={4}
                                  className="mt-1.5 w-full rounded-md border border-slate-300 bg-white px-3 py-2 text-sm focus:border-amber-500 focus:outline-none focus:ring-2 focus:ring-amber-500/20 font-mono" />
                    </div>
                    <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                        <div>
                            <label className="text-xs font-bold uppercase tracking-wider text-slate-700">Téléphone SAV</label>
                            <input data-testid="bs-phone" value={data.sav_phone} onChange={(e) => update('sav_phone', e.target.value)}
                                   className="mt-1.5 w-full h-11 rounded-md border border-slate-300 bg-white px-3 text-sm focus:border-amber-500 focus:outline-none focus:ring-2 focus:ring-amber-500/20" />
                        </div>
                        <div>
                            <label className="text-xs font-bold uppercase tracking-wider text-slate-700">Email SAV</label>
                            <input data-testid="bs-email" type="email" value={data.sav_email} onChange={(e) => update('sav_email', e.target.value)}
                                   className="mt-1.5 w-full h-11 rounded-md border border-slate-300 bg-white px-3 text-sm focus:border-amber-500 focus:outline-none focus:ring-2 focus:ring-amber-500/20" />
                        </div>
                    </div>
                    <div>
                        <label className="text-xs font-bold uppercase tracking-wider text-slate-700">Température par défaut</label>
                        <input data-testid="bs-temp" value={data.temperature_default} onChange={(e) => update('temperature_default', e.target.value)} placeholder="ex. +2 / +4 °C"
                               className="mt-1.5 w-full h-11 rounded-md border border-slate-300 bg-white px-3 text-sm focus:border-amber-500 focus:outline-none focus:ring-2 focus:ring-amber-500/20" />
                        <p className="mt-1 text-[11px] text-slate-500">Utilisée dans le PDF quand le bordereau n'a pas de température spécifique.</p>
                    </div>
                    <div>
                        <label className="text-xs font-bold uppercase tracking-wider text-slate-700">Texte IMPORTANT (bas du bordereau)</label>
                        <textarea data-testid="bs-important" value={data.important_text} onChange={(e) => update('important_text', e.target.value)} rows={5}
                                  className="mt-1.5 w-full rounded-md border border-slate-300 bg-white px-3 py-2 text-sm focus:border-amber-500 focus:outline-none focus:ring-2 focus:ring-amber-500/20" />
                    </div>
                </div>
                <div className="px-5 py-3 border-t border-slate-200 flex justify-end gap-2">
                    <button onClick={onClose} className="rounded-md border border-slate-300 px-4 h-10 text-sm font-bold hover:bg-slate-50">Annuler</button>
                    <button onClick={save} disabled={saving} data-testid="bs-save" className="inline-flex items-center gap-2 rounded-md bg-amber-500 text-white px-5 h-10 text-sm font-heading font-bold hover:bg-amber-600 active:scale-[0.99] transition-all disabled:opacity-60">
                        <Save className="h-4 w-4" /> {saving ? 'Enregistrement…' : 'Enregistrer'}
                    </button>
                </div>
            </div>
        </div>
    );
}
