import React, { useEffect, useMemo, useState } from 'react';
import { api } from '../../lib/api';
import { toast } from 'sonner';
import { Search, X, MapPin, Truck, Building2, Plus } from 'lucide-react';

/**
 * Format a sav_client record into the multi-line text used inside the
 * Transporteur / Destinataire textareas of the bordereau.
 */
export function formatClientForBordereau(c) {
    if (!c) return '';
    const lines = [];
    if (c.name) lines.push(c.name);
    if (c.address) lines.push(c.address);
    const cityLine = [c.postal_code, c.city].filter(Boolean).join(' ').trim();
    if (cityLine) lines.push(cityLine);
    if (c.country) lines.push(c.country);
    if (c.contact_name || c.phone) {
        const ct = [c.contact_name, c.phone].filter(Boolean).join(' · ').trim();
        if (ct) lines.push(ct);
    }
    return lines.join('\n');
}

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

/**
 * Modal that lets the user pick a saved client (filtered by kind) to
 * fill the Transporteur or Destinataire field of a bordereau.
 *
 * Props:
 *  - kind: 'transporteur' | 'destinataire'
 *  - onPick(client)
 *  - onClose()
 *  - onManage() optional → open the full clients page (Carnet)
 */
export default function ClientPickerModal({ kind, onPick, onClose, onManage }) {
    const [items, setItems] = useState([]);
    const [q, setQ] = useState('');
    const [loading, setLoading] = useState(true);
    const Icon = kind === 'transporteur' ? Truck : Building2;
    const title = kind === 'transporteur' ? 'Choisir un transporteur' : 'Choisir un destinataire';

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

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

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

    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={`client-picker-${kind}`}>
            <div className="bg-white rounded-lg shadow-xl w-full max-w-xl 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 flex items-center gap-2">
                        <Icon className="h-5 w-5 text-amber-500" /> {title}
                    </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="client-picker-close">
                        <X className="h-5 w-5" />
                    </button>
                </div>

                <div className="px-5 py-3 border-b border-slate-200 flex items-center gap-2">
                    <div className="relative flex-1">
                        <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400" />
                        <input
                            data-testid="client-picker-search"
                            autoFocus
                            value={q}
                            onChange={(e) => setQ(e.target.value)}
                            placeholder="Rechercher par nom, ville, contact…"
                            className="w-full h-10 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>
                    {onManage && (
                        <button
                            data-testid="client-picker-manage"
                            onClick={onManage}
                            className="inline-flex items-center gap-1.5 rounded-md border border-amber-300 text-amber-700 bg-amber-50 px-3 h-10 text-xs font-bold hover:bg-amber-100"
                            title="Gérer le carnet d'adresses"
                        >
                            <Plus className="h-3.5 w-3.5" /> Nouveau
                        </button>
                    )}
                </div>

                <div className="px-2 py-2 max-h-[60vh] overflow-y-auto">
                    {loading ? (
                        <p className="text-center text-sm text-slate-500 py-10">Chargement…</p>
                    ) : filtered.length === 0 ? (
                        <div className="text-center py-10">
                            <p className="text-sm text-slate-500">Aucun client trouvé.</p>
                            {onManage && (
                                <button
                                    onClick={onManage}
                                    className="mt-3 inline-flex items-center gap-1.5 rounded-md bg-amber-500 text-white px-4 h-9 text-xs font-bold hover:bg-amber-600"
                                >
                                    <Plus className="h-3.5 w-3.5" /> Créer un client
                                </button>
                            )}
                        </div>
                    ) : (
                        <ul className="divide-y divide-slate-100">
                            {filtered.map((c) => {
                                const sub = [c.address, [c.postal_code, c.city].filter(Boolean).join(' '), c.country]
                                    .filter(Boolean).join(' · ');
                                return (
                                    <li key={c.id}>
                                        <button
                                            data-testid={`client-picker-item-${c.id}`}
                                            onClick={() => onPick(c)}
                                            className="w-full text-left px-3 py-2.5 rounded-md hover:bg-amber-50 focus:bg-amber-50 outline-none transition group"
                                        >
                                            <div className="flex items-center gap-2">
                                                <p className="font-bold text-slate-900 truncate">{c.name}</p>
                                                <span className="text-[10px] uppercase tracking-wider font-bold text-amber-700 bg-amber-100 rounded-full px-2 py-0.5">
                                                    {KIND_LABEL[c.kind] || c.kind}
                                                </span>
                                            </div>
                                            {sub && (
                                                <p className="mt-0.5 text-xs text-slate-500 flex items-start gap-1.5">
                                                    <MapPin className="h-3 w-3 mt-0.5 shrink-0" />
                                                    <span className="truncate">{sub}</span>
                                                </p>
                                            )}
                                        </button>
                                    </li>
                                );
                            })}
                        </ul>
                    )}
                </div>
            </div>
        </div>
    );
}
