import React, { useEffect, useState } from 'react';
import Layout from '../../components/Layout';
import { api } from '../../lib/api';
import { useNavigate, useParams } from 'react-router-dom';
import { toast } from 'sonner';
import { ArrowLeft, Save, Trash2, Archive, ArchiveRestore, Boxes, Barcode } from 'lucide-react';

const empty = {
    nombre_palettes: 1,
    produit: '', fournisseur: '', klstb: '', sscc: '', gtin: '',
    motif: '', zone: '', commentaire: '',
};

export default function PaletteForm() {
    const { id } = useParams();
    const isEdit = !!id;
    const navigate = useNavigate();
    const [form, setForm] = useState(empty);
    const [motifs, setMotifs] = useState([]);
    const [zones, setZones] = useState([]);
    const [loading, setLoading] = useState(isEdit);
    const [saving, setSaving] = useState(false);
    const [archived, setArchived] = useState(false);
    const [ssccBusy, setSsccBusy] = useState(false);
    const [ssccDup, setSsccDup] = useState(false);

    useEffect(() => {
        (async () => {
            try {
                const [m, z] = await Promise.all([api.get('/gp/motifs'), api.get('/gp/zones')]);
                setMotifs(m.data || []);
                setZones(z.data || []);
                if (isEdit) {
                    const r = await api.get(`/gp/palettes/${id}`);
                    setForm({
                        nombre_palettes: r.data.nombre_palettes || 1,
                        produit: r.data.produit || '',
                        fournisseur: r.data.fournisseur || '',
                        klstb: r.data.klstb || '',
                        sscc: r.data.sscc || '',
                        gtin: r.data.gtin || '',
                        motif: r.data.motif || '',
                        zone: r.data.zone || '',
                        commentaire: r.data.commentaire || '',
                    });
                    setArchived(r.data.archived || false);
                }
            } catch (err) {
                toast.error(err?.response?.data?.detail || 'Erreur chargement');
                navigate('/palettes/reliquat');
            } finally {
                setLoading(false);
            }
        })();
    }, [id, isEdit, navigate]);

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

    // Toggle a motif on/off (multi-select stored as CSV)
    const toggleMotif = (label) => {
        const cur = (form.motif || '').split(',').map(s => s.trim()).filter(Boolean);
        const idx = cur.indexOf(label);
        if (idx >= 0) cur.splice(idx, 1);
        else cur.push(label);
        update('motif', cur.join(', '));
    };
    const isMotifSelected = (label) => (form.motif || '').split(',').map(s => s.trim()).includes(label);

    // Live check for SSCC duplicates while typing
    useEffect(() => {
        const sscc = (form.sscc || '').trim();
        if (!sscc) { setSsccDup(false); return; }
        setSsccBusy(true);
        const t = setTimeout(async () => {
            try {
                const r = await api.get('/gp/palettes/check-sscc', { params: { sscc, exclude_id: id || 0 } });
                setSsccDup(!!r.data?.exists);
            } catch (_) { setSsccDup(false); }
            finally { setSsccBusy(false); }
        }, 400);
        return () => clearTimeout(t);
    }, [form.sscc, id]);

    const save = async () => {
        if (ssccDup) { toast.error('Le SSCC existe déjà.'); return; }
        setSaving(true);
        try {
            if (isEdit) {
                await api.patch(`/gp/palettes/${id}`, form);
                toast.success('Palette mise à jour');
            } else {
                const r = await api.post('/gp/palettes', form);
                toast.success(`Palette créée`);
            }
            navigate('/palettes/reliquat');
        } catch (err) {
            toast.error(err?.response?.data?.detail || 'Erreur');
        } finally {
            setSaving(false);
        }
    };

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

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

    if (loading) return <Layout><div className="text-slate-500">Chargement…</div></Layout>;

    return (
        <Layout>
            <button onClick={() => navigate('/palettes/reliquat')} className="mb-4 inline-flex items-center gap-2 text-sm text-slate-600 hover:text-amber-600 transition" data-testid="palette-back">
                <ArrowLeft className="h-4 w-4" /> Retour à la liste
            </button>

            <div className="mb-6">
                <p className="text-xs font-bold uppercase tracking-[0.2em] text-amber-600">Reliquat</p>
                <h1 className="mt-2 font-heading text-2xl sm:text-3xl font-black tracking-tight text-slate-900">{isEdit ? 'Palette' : 'Nouvelle palette'}</h1>
            </div>

            <div className="max-w-3xl space-y-5">
                <div className="rounded-lg border border-slate-200 bg-white p-5 sm:p-6">
                    <h2 className="font-heading text-base font-bold text-slate-900 mb-4 flex items-center gap-2"><Boxes className="h-4 w-4 text-amber-500" /> Informations</h2>

                    <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label className="text-xs font-bold uppercase tracking-wider text-slate-700">Nombre de palettes</label>
                            <input data-testid="p-nombre" type="number" min={1} value={form.nombre_palettes} onChange={(e) => update('nombre_palettes', Math.max(1, parseInt(e.target.value || 1)))} className="mt-1.5 w-full h-11 rounded-md border border-slate-300 bg-white px-3 text-base font-medium 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">Zone</label>
                            <select data-testid="p-zone" value={form.zone} onChange={(e) => update('zone', e.target.value)} className="mt-1.5 w-full h-11 rounded-md border border-slate-300 bg-white px-3 text-base font-medium focus:border-amber-500 focus:outline-none focus:ring-2 focus:ring-amber-500/20">
                                <option value="">— Non définie —</option>
                                {zones.map(z => <option key={z.id} value={z.label}>{z.label}</option>)}
                            </select>
                        </div>

                        <div>
                            <label className="text-xs font-bold uppercase tracking-wider text-slate-700">Produit</label>
                            <input data-testid="p-produit" value={form.produit} onChange={(e) => update('produit', e.target.value)} placeholder="Désignation du produit" className="mt-1.5 w-full h-11 rounded-md border border-slate-300 bg-white px-3 text-base font-medium 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">Fournisseur</label>
                            <input data-testid="p-fournisseur" value={form.fournisseur} onChange={(e) => update('fournisseur', e.target.value)} placeholder="Nom du fournisseur" className="mt-1.5 w-full h-11 rounded-md border border-slate-300 bg-white px-3 text-base font-medium 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">KLSTB</label>
                            <input data-testid="p-klstb" value={form.klstb} onChange={(e) => update('klstb', e.target.value)} placeholder="N° colis" className="mt-1.5 w-full h-11 rounded-md border border-slate-300 bg-white px-3 text-base font-medium 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">GTIN</label>
                            <input data-testid="p-gtin" value={form.gtin} onChange={(e) => update('gtin', e.target.value)} placeholder="Code GTIN" className="mt-1.5 w-full h-11 rounded-md border border-slate-300 bg-white px-3 font-mono text-base focus:border-amber-500 focus:outline-none focus:ring-2 focus:ring-amber-500/20" />
                        </div>

                        <div className="md:col-span-2">
                            <label className="text-xs font-bold uppercase tracking-wider text-slate-700">SSCC <span className="text-slate-400">(scanner ou saisir)</span></label>
                            <div className="mt-1.5 relative">
                                <Barcode className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400 pointer-events-none" />
                                <input data-testid="p-sscc" value={form.sscc} onChange={(e) => update('sscc', e.target.value)} placeholder="00 + 18 chiffres" autoComplete="off" className={`w-full h-11 rounded-md border bg-white pl-10 pr-3 font-mono text-base focus:outline-none focus:ring-2 transition ${ssccDup ? 'border-red-500 ring-red-200' : 'border-slate-300 focus:border-amber-500 focus:ring-amber-500/20'}`} />
                            </div>
                            {ssccBusy && <p className="mt-1.5 text-[11px] text-slate-400">Vérification…</p>}
                            {ssccDup && <p data-testid="p-sscc-dup" className="mt-1.5 text-[11px] font-bold text-red-600">Ce SSCC existe déjà.</p>}
                        </div>
                    </div>
                </div>

                <div className="rounded-lg border border-slate-200 bg-white p-5 sm:p-6">
                    <h2 className="font-heading text-base font-bold text-slate-900 mb-4">Motif(s)</h2>
                    {motifs.length === 0 ? (
                        <p className="text-sm text-slate-500 italic">Aucun motif configuré.</p>
                    ) : (
                        <div className="flex flex-wrap gap-2" data-testid="p-motifs">
                            {motifs.map(m => (
                                <button
                                    key={m.id}
                                    type="button"
                                    data-testid={`p-motif-${m.id}`}
                                    onClick={() => toggleMotif(m.label)}
                                    className={`inline-flex items-center gap-2 rounded-full border px-3.5 h-9 text-xs font-heading font-bold uppercase tracking-wider transition ${
                                        isMotifSelected(m.label)
                                            ? 'bg-amber-500 text-white border-amber-500'
                                            : 'bg-white text-slate-700 border-slate-300 hover:border-amber-500 hover:text-amber-600'
                                    }`}
                                >
                                    {m.label}
                                </button>
                            ))}
                        </div>
                    )}
                </div>

                <div className="rounded-lg border border-slate-200 bg-white p-5 sm:p-6">
                    <label className="text-xs font-bold uppercase tracking-wider text-slate-700">Commentaire</label>
                    <textarea data-testid="p-commentaire" rows={3} value={form.commentaire} onChange={(e) => update('commentaire', e.target.value)} placeholder="Notes, précisions, observations…" 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 className="flex flex-wrap items-center justify-between gap-3">
                    <div className="flex gap-2">
                        {isEdit && (
                            <>
                                <button data-testid="p-archive-btn" onClick={toggleArchive} className="inline-flex items-center gap-2 rounded-md border border-slate-300 bg-white px-4 h-11 text-sm font-bold text-slate-700 hover:bg-slate-50">
                                    {archived ? <><ArchiveRestore className="h-4 w-4" /> Restaurer</> : <><Archive className="h-4 w-4" /> Archiver</>}
                                </button>
                                <button data-testid="p-delete-btn" onClick={del} className="inline-flex items-center gap-2 rounded-md border border-red-300 bg-white px-4 h-11 text-sm font-bold text-red-700 hover:bg-red-50">
                                    <Trash2 className="h-4 w-4" /> Supprimer
                                </button>
                            </>
                        )}
                    </div>
                    <button data-testid="p-save-btn" onClick={save} disabled={saving || ssccDup} className="inline-flex items-center gap-2 rounded-md bg-amber-500 text-white px-6 h-11 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…' : (isEdit ? 'Enregistrer' : 'Créer la palette')}
                    </button>
                </div>
            </div>
        </Layout>
    );
}
