/**
 * TaxiBook Partner - Vouchers View ("Bons clients")
 * ==================================================
 * Création de QR codes voucher débitant la carte du partenaire à chaque scan chauffeur.
 */

const fmtCents = (c) => (Number(c || 0) / 100).toFixed(2) + ' CHF';
const fmtDateOnly = (s) => {
    if (!s) return '-';
    try { const d = new Date(s.indexOf('T') !== -1 ? s : s.replace(' ', 'T') + 'Z'); return d.toLocaleDateString('fr-CH', { day: '2-digit', month: '2-digit', year: 'numeric' }); } catch (e) { return s; }
};
const fmtDateTime = (s) => {
    if (!s) return '-';
    try { const d = new Date(s.indexOf('T') !== -1 ? s : s.replace(' ', 'T') + 'Z'); return d.toLocaleString('fr-CH', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' }); } catch (e) { return s; }
};
const statusColor = (s) => {
    if (s === 'active')   return { cls: 'bg-green-100 text-green-700', label: 'Actif' };
    if (s === 'pending')  return { cls: 'bg-yellow-100 text-yellow-700', label: 'En attente' };
    if (s === 'expired')  return { cls: 'bg-red-100 text-red-700', label: 'Expiré' };
    if (s === 'consumed') return { cls: 'bg-indigo-100 text-indigo-700', label: 'Épuisé' };
    if (s === 'disabled') return { cls: 'bg-gray-200 text-gray-700', label: 'Désactivé' };
    return { cls: 'bg-gray-100 text-gray-600', label: s || '-' };
};

const QRBox = ({ value, size = 180 }) => {
    const ref = React.useRef(null);
    React.useEffect(() => {
        if (!ref.current || !window.QRCode || !value) return;
        try { window.QRCode.toCanvas(ref.current, value, { width: size, margin: 1 }, (err) => { if (err) console.error(err); }); } catch (e) { console.error(e); }
    }, [value, size]);
    return <canvas ref={ref} className="rounded-xl bg-white" />;
};

const VoucherCreateModal = ({ onClose, onCreated, setToast }) => {
    const [cards, setCards] = React.useState([]);
    const [cardId, setCardId] = React.useState('');
    const [loadingCards, setLoadingCards] = React.useState(true);
    const [name, setName] = React.useState('');
    const [phone, setPhone] = React.useState('');
    const [email, setEmail] = React.useState('');
    const [amount, setAmount] = React.useState('');
    const today = new Date();
    const ymd = (d) => d.getFullYear() + '-' + String(d.getMonth()+1).padStart(2,'0') + '-' + String(d.getDate()).padStart(2,'0');
    const monthLater = new Date(); monthLater.setMonth(monthLater.getMonth() + 1);
    const [from, setFrom] = React.useState(ymd(today));
    const [until, setUntil] = React.useState(ymd(monthLater));
    const [notes, setNotes] = React.useState('');
    const [saving, setSaving] = React.useState(false);
    const [err, setErr] = React.useState('');

    React.useEffect(() => {
        window.partnerAPI.getVoucherCards().then(r => {
            const list = r.cards || [];
            setCards(list);
            if (list.length > 0) setCardId(String(list[0].id));
            setLoadingCards(false);
        }).catch(() => setLoadingCards(false));
    }, []);

    const submit = async () => {
        setErr('');
        if (!cardId) { setErr('Sélectionnez une carte'); return; }
        if (!name.trim()) { setErr('Nom du client requis'); return; }
        const amt = parseFloat(amount);
        if (!amt || amt <= 0) { setErr('Montant invalide'); return; }
        setSaving(true);
        try {
            const r = await window.partnerAPI.createVoucher({
                payment_card_id: parseInt(cardId),
                client_name: name.trim(),
                client_phone: phone.trim() || null,
                client_email: email.trim() || null,
                max_amount_cents: Math.round(amt * 100),
                valid_from: from + 'T00:00:00.000Z',
                valid_until: until + 'T23:59:59.999Z',
                notes: notes.trim() || null
            });
            setSaving(false);
            if (r.success) {
                setToast && setToast({ message: 'Bon créé avec succès', type: 'success' });
                onCreated && onCreated(r.voucher);
            } else setErr(r.error || 'Erreur création');
        } catch (e) { setSaving(false); setErr('Erreur réseau'); }
    };

    return (
        <div className="fixed inset-0 bg-black/60 z-50 flex items-center justify-center p-4" onClick={(e) => e.target === e.currentTarget && onClose()}>
            <div className="bg-white rounded-2xl w-full max-w-lg shadow-2xl flex flex-col max-h-[90vh]">
                <div className="p-5 border-b border-gray-200 flex items-center justify-between">
                    <h3 className="text-lg font-bold flex items-center gap-2"><i className="fas fa-ticket text-primary-500"></i> Nouveau bon client</h3>
                    <button onClick={onClose} className="text-gray-400 hover:text-gray-600 w-8 h-8 rounded-lg flex items-center justify-center"><i className="fas fa-times"></i></button>
                </div>
                <div className="p-5 overflow-y-auto">
                    {err && <div className="bg-red-50 border border-red-200 text-red-700 text-sm font-semibold p-3 rounded-lg mb-3">{err}</div>}
                    {loadingCards ? (
                        <div className="text-center text-gray-500 py-6">Chargement des cartes…</div>
                    ) : cards.length === 0 ? (
                        <div className="bg-yellow-50 border border-yellow-200 text-yellow-800 p-4 rounded-xl text-center">
                            <i className="fas fa-triangle-exclamation text-2xl mb-2"></i>
                            <div className="font-bold mb-1">Aucune carte enregistrée</div>
                            <div className="text-xs">Enregistrez une carte bancaire dans la section "Cartes" avant de créer un bon.</div>
                        </div>
                    ) : (
                        <div className="space-y-3">
                            <div>
                                <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">Carte à débiter</label>
                                <select value={cardId} onChange={(e) => setCardId(e.target.value)} className="w-full px-3 py-2.5 border-2 border-gray-200 rounded-lg font-semibold focus:border-primary-500 focus:outline-none bg-white">
                                    {cards.map(c => (
                                        <option key={c.id} value={c.id}>{(c.card_brand || 'Carte')} •••• {c.card_last4 || '****'}{c.is_default ? ' (par défaut)' : ''}</option>
                                    ))}
                                </select>
                            </div>
                            <div>
                                <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">Nom du client</label>
                                <input value={name} onChange={(e) => setName(e.target.value)} placeholder="Ex: M. Dupont chambre 412" className="w-full px-3 py-2.5 border-2 border-gray-200 rounded-lg font-semibold focus:border-primary-500 focus:outline-none" />
                            </div>
                            <div className="grid grid-cols-2 gap-3">
                                <div>
                                    <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">Téléphone</label>
                                    <input value={phone} onChange={(e) => setPhone(e.target.value)} placeholder="+41…" className="w-full px-3 py-2.5 border-2 border-gray-200 rounded-lg font-semibold focus:border-primary-500 focus:outline-none" />
                                </div>
                                <div>
                                    <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">Email</label>
                                    <input value={email} onChange={(e) => setEmail(e.target.value)} placeholder="client@…" className="w-full px-3 py-2.5 border-2 border-gray-200 rounded-lg font-semibold focus:border-primary-500 focus:outline-none" />
                                </div>
                            </div>
                            <div>
                                <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">Montant maximum (CHF)</label>
                                <input type="number" step="0.01" value={amount} onChange={(e) => setAmount(e.target.value)} placeholder="50.00" className="w-full px-3 py-2.5 border-2 border-gray-200 rounded-lg font-semibold focus:border-primary-500 focus:outline-none" />
                            </div>
                            <div className="grid grid-cols-2 gap-3">
                                <div>
                                    <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">Valide du</label>
                                    <input type="date" value={from} onChange={(e) => setFrom(e.target.value)} className="w-full px-3 py-2.5 border-2 border-gray-200 rounded-lg font-semibold focus:border-primary-500 focus:outline-none" />
                                </div>
                                <div>
                                    <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">Jusqu'au</label>
                                    <input type="date" value={until} onChange={(e) => setUntil(e.target.value)} className="w-full px-3 py-2.5 border-2 border-gray-200 rounded-lg font-semibold focus:border-primary-500 focus:outline-none" />
                                </div>
                            </div>
                            <div>
                                <label className="block text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">Notes (optionnel)</label>
                                <textarea value={notes} onChange={(e) => setNotes(e.target.value)} rows={2} className="w-full px-3 py-2.5 border-2 border-gray-200 rounded-lg font-semibold focus:border-primary-500 focus:outline-none resize-y" />
                            </div>
                            <button onClick={submit} disabled={saving} className="w-full px-4 py-3 bg-gradient-to-r from-primary-500 to-primary-600 text-white font-bold rounded-lg hover:opacity-90 disabled:opacity-50 mt-2">
                                {saving ? 'Création…' : 'Créer le bon'}
                            </button>
                        </div>
                    )}
                </div>
            </div>
        </div>
    );
};

const VoucherDetailModal = ({ voucher, onClose, onChanged, setToast }) => {
    const [data, setData] = React.useState({ voucher, uses: [] });
    const [loading, setLoading] = React.useState(true);
    const [confirmDel, setConfirmDel] = React.useState(false);
    const [err, setErr] = React.useState('');

    React.useEffect(() => {
        if (!voucher?.uid) return;
        window.partnerAPI.getVoucher(voucher.uid).then(r => {
            if (r.success) setData({ voucher: r.voucher, uses: r.uses || [] });
            setLoading(false);
        }).catch(() => setLoading(false));
    }, [voucher?.uid]);

    const v = data.voucher || voucher;
    const sb = statusColor(v.computed_status || v.status);
    const card = v.payment_card || {};

    const toggleStatus = async () => {
        const next = v.status === 'disabled' ? 'active' : 'disabled';
        const r = await window.partnerAPI.updateVoucher(v.uid, { status: next });
        if (r.success) { setData(prev => ({ voucher: r.voucher, uses: prev.uses })); onChanged && onChanged(); }
        else setErr(r.error || 'Erreur');
    };
    const doDelete = async () => {
        const r = await window.partnerAPI.deleteVoucher(v.uid);
        if (r.success) { setToast && setToast({ message: r.message || 'Bon supprimé', type: 'success' }); onChanged && onChanged(); onClose(); }
        else setErr(r.error || 'Erreur');
    };

    const usedPct = Math.min(100, (Number(v.used_amount_cents || 0) / Math.max(1, Number(v.max_amount_cents || 0))) * 100);

    return (
        <div className="fixed inset-0 bg-black/60 z-50 flex items-center justify-center p-4" onClick={(e) => e.target === e.currentTarget && onClose()}>
            <div className="bg-white rounded-2xl w-full max-w-2xl shadow-2xl flex flex-col max-h-[92vh]">
                <div className="p-5 border-b border-gray-200 flex items-center justify-between">
                    <h3 className="text-lg font-bold flex items-center gap-2"><i className="fas fa-ticket text-primary-500"></i> Bon <code className="text-sm font-mono ml-1">{v.qr_code}</code></h3>
                    <button onClick={onClose} className="text-gray-400 hover:text-gray-600 w-8 h-8 rounded-lg flex items-center justify-center"><i className="fas fa-times"></i></button>
                </div>
                <div className="p-5 overflow-y-auto">
                    {err && <div className="bg-red-50 border border-red-200 text-red-700 text-sm font-semibold p-3 rounded-lg mb-3">{err}</div>}
                    <div className="flex gap-5 mb-5">
                        <div className="flex-shrink-0 p-3 bg-gray-50 border border-gray-200 rounded-2xl">
                            <QRBox value={v.qr_code} size={170} />
                        </div>
                        <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2 mb-2">
                                <span className="text-lg font-bold text-gray-900">{v.client_name || 'Sans nom'}</span>
                                <span className={`text-xs font-bold uppercase tracking-wider px-2.5 py-1 rounded-full ${sb.cls}`}>{sb.label}</span>
                            </div>
                            <div className="text-xs text-gray-500 space-y-0.5 mb-3">
                                {v.client_phone && <div><i className="fas fa-phone w-4 text-gray-400"></i> {v.client_phone}</div>}
                                {v.client_email && <div><i className="fas fa-envelope w-4 text-gray-400"></i> {v.client_email}</div>}
                            </div>
                            <div className="bg-gray-50 border border-gray-200 rounded-xl p-3">
                                <div className="text-xs font-bold text-gray-500 uppercase tracking-wider mb-1">Solde restant</div>
                                <div className="text-2xl font-extrabold text-green-600 mb-1">{fmtCents(v.remaining_amount_cents)}</div>
                                <div className="text-xs font-semibold text-gray-500">sur {fmtCents(v.max_amount_cents)} max</div>
                                <div className="mt-2 h-1.5 bg-gray-200 rounded-full overflow-hidden">
                                    <div className="h-full bg-gradient-to-r from-yellow-500 to-red-500" style={{ width: `${usedPct}%` }} />
                                </div>
                            </div>
                        </div>
                    </div>
                    <div className="grid grid-cols-2 gap-3 text-xs mb-5">
                        <div className="bg-gray-50 rounded-lg p-3">
                            <div className="text-gray-500 font-bold uppercase text-[10px]">Validité</div>
                            <div className="text-gray-900 font-semibold mt-1">{fmtDateOnly(v.valid_from)} → {fmtDateOnly(v.valid_until)}</div>
                        </div>
                        <div className="bg-gray-50 rounded-lg p-3">
                            <div className="text-gray-500 font-bold uppercase text-[10px]">Carte débitée</div>
                            <div className="text-gray-900 font-semibold mt-1">{card.card_brand || '-'} •••• {card.card_last4 || '****'}</div>
                        </div>
                    </div>
                    <div className="text-sm font-bold text-gray-900 mb-2 flex items-center gap-2">
                        <i className="fas fa-receipt text-primary-500"></i>
                        Utilisations
                        <span className="bg-gray-100 text-gray-600 text-xs font-bold px-2 py-0.5 rounded-full">{(data.uses || []).length}</span>
                    </div>
                    {loading ? (
                        <div className="text-center text-gray-400 py-6">Chargement…</div>
                    ) : (data.uses || []).length === 0 ? (
                        <div className="text-center text-gray-400 py-6 bg-gray-50 rounded-xl">Aucune utilisation pour le moment.</div>
                    ) : (
                        <div className="space-y-2">
                            {data.uses.map(u => {
                                const ok = u.worldline_status === 'CAPTURED' || u.worldline_status === 'AUTHORIZED';
                                return (
                                    <div key={u.uid} className={`p-3 border rounded-lg ${ok ? 'bg-white border-gray-200' : 'bg-red-50 border-red-200'}`}>
                                        <div className="flex items-center justify-between mb-1">
                                            <span className={`text-sm font-extrabold ${ok ? 'text-green-600' : 'text-red-600'}`}>{ok ? '−' : '✗ '}{fmtCents(u.amount_cents)}</span>
                                            <span className="text-xs text-gray-500 font-semibold">{fmtDateTime(u.created_at)}</span>
                                        </div>
                                        {(u.j_pickup || u.pickup_address) && <div className="text-xs text-gray-600"><i className="fas fa-circle text-green-500 text-[6px] mr-2"></i>{u.j_pickup || u.pickup_address}</div>}
                                        {(u.j_dropoff || u.dropoff_address) && <div className="text-xs text-gray-600"><i className="fas fa-circle text-red-500 text-[6px] mr-2"></i>{u.j_dropoff || u.dropoff_address}</div>}
                                        <div className="flex justify-between mt-1.5 text-xs text-gray-500">
                                            <span>{u.driver_name ? `Chauffeur : ${u.driver_name}` : ''}</span>
                                            {ok && <span>Reste : {fmtCents(u.remaining_after_cents)}</span>}
                                        </div>
                                        {u.error_message && <div className="mt-1 text-xs text-red-600 font-semibold">{u.error_message}</div>}
                                    </div>
                                );
                            })}
                        </div>
                    )}
                    <div className="flex gap-2 mt-5">
                        <button onClick={toggleStatus} className="flex-1 px-3 py-2.5 border border-gray-200 rounded-lg font-bold text-sm text-gray-700 hover:bg-gray-50">
                            {v.status === 'disabled' ? 'Réactiver' : 'Désactiver'}
                        </button>
                        {!confirmDel ? (
                            <button onClick={() => setConfirmDel(true)} className="flex-1 px-3 py-2.5 bg-red-50 border border-red-200 text-red-600 font-bold text-sm rounded-lg hover:bg-red-100">Supprimer</button>
                        ) : (
                            <button onClick={doDelete} className="flex-1 px-3 py-2.5 bg-red-600 border border-red-700 text-white font-bold text-sm rounded-lg hover:bg-red-700">Confirmer la suppression</button>
                        )}
                    </div>
                </div>
            </div>
        </div>
    );
};

const VouchersView = ({ partner, setToast }) => {
    const [list, setList] = React.useState([]);
    const [loading, setLoading] = React.useState(true);
    const [filter, setFilter] = React.useState('all');
    const [search, setSearch] = React.useState('');
    const [showCreate, setShowCreate] = React.useState(false);
    const [selected, setSelected] = React.useState(null);

    const load = async () => {
        setLoading(true);
        try { const r = await window.partnerAPI.getVouchers(); setList(r.vouchers || []); } catch (e) {}
        setLoading(false);
    };
    React.useEffect(() => { load(); }, []);

    const filtered = list.filter(v => {
        if (filter !== 'all') {
            const st = v.computed_status || v.status;
            if (filter === 'active' && st !== 'active' && st !== 'pending') return false;
            if (filter === 'finished' && st !== 'expired' && st !== 'consumed' && st !== 'disabled') return false;
        }
        if (search) {
            const q = search.toLowerCase();
            return (v.client_name || '').toLowerCase().includes(q) ||
                   (v.qr_code || '').toLowerCase().includes(q) ||
                   (v.client_phone || '').toLowerCase().includes(q);
        }
        return true;
    });

    const totals = list.reduce((acc, v) => {
        acc.count++;
        acc.max += Number(v.max_amount_cents || 0);
        acc.used += Number(v.used_amount_cents || 0);
        return acc;
    }, { count: 0, max: 0, used: 0 });

    return (
        <div className="p-6 lg:p-8">
            <div className="flex items-center justify-between mb-6">
                <div>
                    <h1 className="text-2xl font-bold text-gray-900 flex items-center gap-3">
                        <i className="fas fa-ticket text-primary-500"></i>
                        Bons clients
                    </h1>
                    <p className="text-sm text-gray-500 mt-1">{totals.count} bon(s) • {fmtCents(totals.used)} dépensés sur {fmtCents(totals.max)}</p>
                </div>
                <button onClick={() => setShowCreate(true)} className="px-4 py-2.5 bg-gradient-to-r from-primary-500 to-primary-600 text-white font-bold rounded-xl hover:opacity-90 flex items-center gap-2">
                    <i className="fas fa-plus"></i> Nouveau bon
                </button>
            </div>

            <div className="bg-white rounded-2xl border border-gray-200 p-4 mb-4 flex flex-wrap gap-3 items-center">
                <div className="relative flex-1 min-w-[200px]">
                    <i className="fas fa-search absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
                    <input value={search} onChange={(e) => setSearch(e.target.value)} placeholder="Rechercher (nom, code, tél…)" className="w-full pl-10 pr-3 py-2.5 border-2 border-gray-200 rounded-lg font-semibold focus:border-primary-500 focus:outline-none" />
                </div>
                <div className="flex gap-1 bg-gray-100 rounded-lg p-1">
                    {['all', 'active', 'finished'].map(f => {
                        const labels = { all: 'Tous', active: 'Actifs', finished: 'Terminés' };
                        return (
                            <button key={f} onClick={() => setFilter(f)} className={`px-3 py-1.5 rounded-md text-sm font-bold ${filter === f ? 'bg-white text-gray-900 shadow-sm' : 'text-gray-500'}`}>
                                {labels[f]}
                            </button>
                        );
                    })}
                </div>
            </div>

            {loading ? (
                <div className="bg-white rounded-2xl border border-gray-200 p-10 text-center text-gray-400">Chargement…</div>
            ) : filtered.length === 0 ? (
                <div className="bg-white rounded-2xl border border-gray-200 p-10 text-center text-gray-400">
                    <i className="fas fa-ticket text-4xl text-gray-300 mb-3"></i>
                    <p>{list.length === 0 ? 'Aucun bon créé pour le moment.' : 'Aucun bon ne correspond à votre filtre.'}</p>
                </div>
            ) : (
                <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
                    {filtered.map(v => {
                        const sb = statusColor(v.computed_status || v.status);
                        const pct = Math.min(100, (Number(v.used_amount_cents || 0) / Math.max(1, Number(v.max_amount_cents || 0))) * 100);
                        return (
                            <div key={v.uid} onClick={() => setSelected(v)} className="bg-white border border-gray-200 rounded-2xl p-4 cursor-pointer hover:shadow-lg hover:border-primary-300 transition">
                                <div className="flex items-center justify-between mb-2">
                                    <div className="font-bold text-gray-900 truncate">{v.client_name || 'Sans nom'}</div>
                                    <span className={`text-[10px] font-bold uppercase tracking-wider px-2 py-1 rounded-full whitespace-nowrap ${sb.cls}`}>{sb.label}</span>
                                </div>
                                <div className="text-xs text-gray-500 font-mono mb-3">{v.qr_code}</div>
                                <div className="flex items-center justify-between mb-1 text-sm">
                                    <span className="text-gray-500">{fmtCents(v.used_amount_cents)} utilisés</span>
                                    <span className="text-green-600 font-bold">{fmtCents(v.remaining_amount_cents)}</span>
                                </div>
                                <div className="h-1.5 bg-gray-200 rounded-full overflow-hidden mb-2">
                                    <div className="h-full bg-gradient-to-r from-yellow-500 to-red-500" style={{ width: `${pct}%` }} />
                                </div>
                                <div className="flex items-center justify-between text-xs text-gray-400">
                                    <span>Jusqu'au {fmtDateOnly(v.valid_until)}</span>
                                    <span>{(v.uses_count || 0)} utilisation{(v.uses_count || 0) > 1 ? 's' : ''}</span>
                                </div>
                            </div>
                        );
                    })}
                </div>
            )}

            {showCreate && <VoucherCreateModal setToast={setToast} onClose={() => setShowCreate(false)} onCreated={() => { setShowCreate(false); load(); }} />}
            {selected && <VoucherDetailModal voucher={selected} setToast={setToast} onClose={() => setSelected(null)} onChanged={() => { load(); }} />}
        </div>
    );
};

window.VouchersView = VouchersView;
