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 {
    ArrowLeft, Plus, Search, Pencil, Trash2, Save, X,
    Truck, Building2, Users, Phone, Mail, MapPin,
} from 'lucide-react';

const KIND_LABEL = {
    transporteur: 'Transporteur',
    destinataire: 'Destinataire',
    both: 'Les deux',
};

const KIND_BADGE = {
    transporteur: 'bg-amber-100 text-amber-800',
    destinataire: 'bg-blue-100 text-blue-800',
    both: 'bg-emerald-100 text-emerald-800',
};

const emptyForm = () => ({
    id: null, name: '', kind: 'both',
    address: '', postal_code: '', city: '', country: '',
    contact_name: '', phone: '', email: '', notes: '',
});

export default function SavClients() {
    const navigate = useNavigate();
    const [items, setItems] = useState([]);
    const [q, setQ] = useState('');
    const [kindFilter, setKindFilter] = useState('both');
    const [loading, setLoading] = useState(true);
    const [editing, setEditing] = useState(null); // form object or null

    const load = async () => {
        setLoading(true);
        try {
            const r = await api.get('/gp/sav-clients', {
                params: { q: q.trim() || undefined, kind: kindFilter },
            });
            setItems(r.data?.items || []);
        } catch (err) {
            toast.error(err?.response?.data?.detail || 'Erreur chargement');
        } finally { setLoading(false); }
    };

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

    const filtered = useMemo(() => items, [items]);

    const onSave = async (form) => {
        const name = (form.name || '').trim();
        if (!name) { toast.error('Le nom du client est obligatoire'); return; }
        try {
            const payload = { ...form, name };
            if (form.id) {
                await api.patch(`/gp/sav-clients/${form.id}`, payload);
                toast.success('Client mis à jour');
            } else {
                await api.post('/gp/sav-clients', payload);
                toast.success('Client créé');
            }
            setEditing(null);
            load();
        } catch (err) {
            toast.error(err?.response?.data?.detail || 'Erreur sauvegarde');
        }
    };

    const onDelete = async (c) => {
        if (!window.confirm(`Supprimer le client "${c.name}" ?`)) return;
        try {
            await api.delete(`/gp/sav-clients/${c.id}`);
            toast.success('Client supprimé');
            load();
        } catch (err) {
            toast.error(err?.response?.data?.detail || 'Erreur');
        }
    };

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

            <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">Carnet d&apos;adresses</p>
                    <h1 className="mt-2 font-heading text-2xl sm:text-3xl lg:text-4xl font-black tracking-tight text-slate-900">
                        Clients (Transporteurs &amp; Destinataires)
                    </h1>
                    <p className="mt-1.5 text-sm sm:text-base text-slate-600">
                        Crée tes clients une seule fois — ils seront ré-utilisables sur tous tes bordereaux.
                    </p>
                </div>
                <button
                    data-testid="sav-clients-new"
                    onClick={() => setEditing(emptyForm())}
                    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 client
                </button>
            </div>

            <div className="mb-4 flex flex-wrap items-center gap-2">
                <div className="relative flex-1 min-w-[220px] max-w-md">
                    <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
                    <input
                        data-testid="sav-clients-search"
                        value={q}
                        onChange={(e) => setQ(e.target.value)}
                        placeholder="Nom, ville, contact…"
                        className="w-full h-11 rounded-md border border-slate-300 bg-white pl-9 pr-3 text-sm focus:border-amber-500 focus:outline-none focus:ring-2 focus:ring-amber-500/20"
                    />
                </div>
                <div className="flex gap-2" data-testid="sav-clients-filters">
                    {[
                        { id: 'both', label: 'Tous', icon: Users },
                        { id: 'transporteur', label: 'Transporteurs', icon: Truck },
                        { id: 'destinataire', label: 'Destinataires', icon: Building2 },
                    ].map(({ id, label, icon: Icon }) => (
                        <button
                            key={id}
                            data-testid={`sav-clients-filter-${id}`}
                            onClick={() => setKindFilter(id)}
                            className={`inline-flex items-center gap-1.5 rounded-full border px-4 h-10 text-xs font-heading font-bold uppercase tracking-wider transition ${
                                kindFilter === 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'
                            }`}
                        >
                            <Icon className="h-3.5 w-3.5" /> {label}
                        </button>
                    ))}
                </div>
            </div>

            {loading ? (
                <div className="rounded-lg border border-slate-200 bg-white p-12 text-center text-slate-500">Chargement…</div>
            ) : filtered.length === 0 ? (
                <div className="rounded-lg border border-dashed border-slate-300 bg-white p-12 text-center">
                    <Users className="mx-auto h-10 w-10 text-slate-300" />
                    <p className="mt-3 font-heading font-bold text-slate-700">Aucun client</p>
                    <p className="mt-1 text-xs text-slate-500">Crée ton premier client pour ne plus retaper ses coordonnées à chaque bordereau.</p>
                </div>
            ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3" data-testid="sav-clients-grid">
                    {filtered.map((c) => (
                        <div
                            key={c.id}
                            data-testid={`sav-client-card-${c.id}`}
                            className="rounded-lg border border-slate-200 bg-white p-4 hover:border-amber-400 transition group"
                        >
                            <div className="flex items-start justify-between gap-2">
                                <div className="min-w-0">
                                    <p className="font-heading font-bold text-slate-900 truncate">{c.name}</p>
                                    <span className={`inline-flex items-center mt-1 rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider ${KIND_BADGE[c.kind] || KIND_BADGE.both}`}>
                                        {KIND_LABEL[c.kind] || c.kind}
                                    </span>
                                </div>
                                <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition">
                                    <button
                                        data-testid={`sav-client-edit-${c.id}`}
                                        onClick={() => setEditing({ ...emptyForm(), ...c })}
                                        className="h-8 w-8 rounded-md hover:bg-amber-100 text-amber-700 flex items-center justify-center"
                                        title="Éditer"
                                    >
                                        <Pencil className="h-3.5 w-3.5" />
                                    </button>
                                    <button
                                        data-testid={`sav-client-delete-${c.id}`}
                                        onClick={() => onDelete(c)}
                                        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 className="mt-3 space-y-1.5 text-xs text-slate-600">
                                {(c.address || c.city || c.country) && (
                                    <div className="flex items-start gap-1.5">
                                        <MapPin className="h-3.5 w-3.5 mt-0.5 text-slate-400 shrink-0" />
                                        <span className="whitespace-pre-line">
                                            {[c.address, [c.postal_code, c.city].filter(Boolean).join(' '), c.country]
                                                .filter(Boolean).join('\n')}
                                        </span>
                                    </div>
                                )}
                                {c.contact_name && (
                                    <div className="flex items-center gap-1.5">
                                        <Users className="h-3.5 w-3.5 text-slate-400 shrink-0" /> {c.contact_name}
                                    </div>
                                )}
                                {c.phone && (
                                    <div className="flex items-center gap-1.5">
                                        <Phone className="h-3.5 w-3.5 text-slate-400 shrink-0" /> {c.phone}
                                    </div>
                                )}
                                {c.email && (
                                    <div className="flex items-center gap-1.5 truncate">
                                        <Mail className="h-3.5 w-3.5 text-slate-400 shrink-0" /> <span className="truncate">{c.email}</span>
                                    </div>
                                )}
                            </div>
                        </div>
                    ))}
                </div>
            )}

            {editing && (
                <ClientFormModal
                    form={editing}
                    onChange={setEditing}
                    onClose={() => setEditing(null)}
                    onSave={onSave}
                />
            )}
        </Layout>
    );
}

function ClientFormModal({ form, onChange, onClose, onSave }) {
    const upd = (k, v) => onChange({ ...form, [k]: v });
    const isEdit = !!form.id;
    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="sav-client-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">
                        {isEdit ? 'Modifier le client' : 'Nouveau client'}
                    </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="sav-client-modal-close">
                        <X className="h-5 w-5" />
                    </button>
                </div>
                <div className="px-5 py-4 space-y-4 max-h-[70vh] overflow-y-auto">
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                        <div className="md:col-span-2">
                            <label className="text-xs font-bold uppercase tracking-wider text-slate-700">Nom *</label>
                            <input
                                data-testid="sav-client-field-name"
                                value={form.name}
                                onChange={(e) => upd('name', e.target.value)}
                                placeholder="ex. STEF Transport / Carrefour Geispolsheim"
                                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">Type</label>
                            <select
                                data-testid="sav-client-field-kind"
                                value={form.kind}
                                onChange={(e) => upd('kind', 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"
                            >
                                <option value="both">Les deux</option>
                                <option value="transporteur">Transporteur</option>
                                <option value="destinataire">Destinataire</option>
                            </select>
                        </div>
                    </div>

                    <div>
                        <label className="text-xs font-bold uppercase tracking-wider text-slate-700">Adresse</label>
                        <textarea
                            data-testid="sav-client-field-address"
                            value={form.address}
                            onChange={(e) => upd('address', e.target.value)}
                            rows={2}
                            placeholder="N° rue, complément…"
                            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="grid grid-cols-1 md:grid-cols-3 gap-3">
                        <div>
                            <label className="text-xs font-bold uppercase tracking-wider text-slate-700">Code postal</label>
                            <input
                                data-testid="sav-client-field-postal"
                                value={form.postal_code}
                                onChange={(e) => upd('postal_code', 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 className="md:col-span-2">
                            <label className="text-xs font-bold uppercase tracking-wider text-slate-700">Ville</label>
                            <input
                                data-testid="sav-client-field-city"
                                value={form.city}
                                onChange={(e) => upd('city', 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">Pays</label>
                        <input
                            data-testid="sav-client-field-country"
                            value={form.country}
                            onChange={(e) => upd('country', e.target.value)}
                            placeholder="France"
                            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 className="grid grid-cols-1 md:grid-cols-3 gap-3">
                        <div>
                            <label className="text-xs font-bold uppercase tracking-wider text-slate-700">Contact</label>
                            <input
                                data-testid="sav-client-field-contact"
                                value={form.contact_name}
                                onChange={(e) => upd('contact_name', e.target.value)}
                                placeholder="Nom / fonction"
                                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">Téléphone</label>
                            <input
                                data-testid="sav-client-field-phone"
                                value={form.phone}
                                onChange={(e) => upd('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</label>
                            <input
                                data-testid="sav-client-field-email"
                                type="email"
                                value={form.email}
                                onChange={(e) => upd('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">Notes</label>
                        <textarea
                            data-testid="sav-client-field-notes"
                            value={form.notes}
                            onChange={(e) => upd('notes', e.target.value)}
                            rows={2}
                            placeholder="Horaires de quai, instructions de livraison…"
                            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" data-testid="sav-client-cancel">Annuler</button>
                    <button
                        data-testid="sav-client-save"
                        onClick={() => onSave(form)}
                        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"
                    >
                        <Save className="h-4 w-4" /> {isEdit ? 'Enregistrer' : 'Créer'}
                    </button>
                </div>
            </div>
        </div>
    );
}
