/**
 * TaxiBook Partner - API Keys View
 * =================================
 * Permet de générer/révoquer des clés API pour applications tierces.
 * Les clés sont validées par un manager avant d'être utilisables sur
 * https://gateway.taxis.ch.
 */

const { useState: useStateApi, useEffect: useEffectApi, useMemo: useMemoApi } = React;

const GATEWAY_BASE = 'https://gateway.taxis.ch';

const API_KEY_STATUS = {
    pending:  { label: 'En attente de validation', icon: 'fa-hourglass-half', bg: 'bg-amber-100',  fg: 'text-amber-700',  border: 'border-amber-200' },
    active:   { label: 'Active',                   icon: 'fa-circle-check',   bg: 'bg-emerald-100', fg: 'text-emerald-700', border: 'border-emerald-200' },
    rejected: { label: 'Refusée',                  icon: 'fa-circle-xmark',   bg: 'bg-rose-100',    fg: 'text-rose-700',    border: 'border-rose-200' },
    revoked:  { label: 'Révoquée',                 icon: 'fa-ban',            bg: 'bg-gray-200',    fg: 'text-gray-700',    border: 'border-gray-200' }
};

function ApiKeyStatusBadge({ status }) {
    const cfg = API_KEY_STATUS[status] || { label: status, icon: 'fa-question', bg: 'bg-gray-100', fg: 'text-gray-700', border: 'border-gray-200' };
    return (
        <span className={`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold border ${cfg.bg} ${cfg.fg} ${cfg.border}`}>
            <i className={`fas ${cfg.icon}`}></i>
            {cfg.label}
        </span>
    );
}

// ============================================================================
// CREATE MODAL — formulaire pour générer une clé
// ============================================================================

function CreateKeyModal({ open, onClose, onCreated, setToast }) {
    const [form, setForm] = useStateApi({ app_name: '', app_url: '', app_description: '', contact_email: '' });
    const [saving, setSaving] = useStateApi(false);
    const [created, setCreated] = useStateApi(null); // { full_key, key }
    const [copied, setCopied] = useStateApi(false);

    useEffectApi(() => {
        if (open) {
            setForm({ app_name: '', app_url: '', app_description: '', contact_email: '' });
            setCreated(null);
            setCopied(false);
        }
    }, [open]);

    if (!open) return null;

    const submit = async (e) => {
        e.preventDefault();
        if (!form.app_name.trim() || form.app_name.trim().length < 2) {
            setToast && setToast({ message: 'Nom de l\'application requis', type: 'error' });
            return;
        }
        setSaving(true);
        try {
            const res = await window.partnerAPI.createApiKey(form);
            if (res.success) {
                setCreated(res.data);
                onCreated && onCreated();
            } else {
                setToast && setToast({ message: res.error || 'Erreur', type: 'error' });
            }
        } catch (err) {
            setToast && setToast({ message: err.message, type: 'error' });
        } finally {
            setSaving(false);
        }
    };

    const copyKey = () => {
        if (!created?.full_key) return;
        navigator.clipboard.writeText(created.full_key);
        setCopied(true);
        setTimeout(() => setCopied(false), 2000);
    };

    return (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4" onClick={() => !saving && onClose()}>
            <div className="bg-white rounded-2xl shadow-xl w-full max-w-lg overflow-hidden" onClick={(e) => e.stopPropagation()}>
                {created ? (
                    <div className="p-6">
                        <div className="flex items-center gap-3 mb-4">
                            <div className="w-12 h-12 rounded-xl bg-emerald-100 text-emerald-600 flex items-center justify-center">
                                <i className="fas fa-key text-xl"></i>
                            </div>
                            <div>
                                <h3 className="text-lg font-bold text-gray-900">Clé créée</h3>
                                <p className="text-xs text-gray-500">Conservez-la maintenant — elle ne sera plus jamais affichée.</p>
                            </div>
                        </div>
                        <div className="bg-amber-50 border border-amber-200 rounded-xl p-3 text-sm text-amber-800 mb-4">
                            <i className="fas fa-triangle-exclamation mr-1"></i>
                            La clé doit encore être <strong>validée par un manager</strong> avant d'être utilisable.
                        </div>
                        <div className="bg-gray-900 text-emerald-300 font-mono text-xs rounded-xl p-3 break-all relative">
                            {created.full_key}
                            <button onClick={copyKey} className="absolute top-2 right-2 bg-gray-800 hover:bg-gray-700 text-white text-[11px] px-2 py-1 rounded">
                                <i className={`fas ${copied ? 'fa-check' : 'fa-copy'} mr-1`}></i>
                                {copied ? 'Copié' : 'Copier'}
                            </button>
                        </div>
                        <button onClick={onClose} className="mt-4 w-full bg-primary-500 hover:bg-primary-600 text-white font-semibold py-2.5 rounded-xl">
                            J'ai copié la clé
                        </button>
                    </div>
                ) : (
                    <form onSubmit={submit} className="p-6">
                        <h3 className="text-lg font-bold text-gray-900 mb-1">Nouvelle clé API</h3>
                        <p className="text-xs text-gray-500 mb-5">Décrivez l'application qui utilisera cette clé. Un manager validera la demande.</p>

                        <label className="block text-xs font-semibold text-gray-700 mb-1">Nom de l'application *</label>
                        <input type="text" required minLength={2} value={form.app_name}
                               onChange={(e) => setForm({...form, app_name: e.target.value})}
                               className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm mb-4"
                               placeholder="Ex: Conciergerie Hotel Beau-Rivage"
                               disabled={saving}/>

                        <label className="block text-xs font-semibold text-gray-700 mb-1">URL de l'application</label>
                        <input type="url" value={form.app_url}
                               onChange={(e) => setForm({...form, app_url: e.target.value})}
                               className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm mb-4"
                               placeholder="https://..."
                               disabled={saving}/>

                        <label className="block text-xs font-semibold text-gray-700 mb-1">Email de contact</label>
                        <input type="email" value={form.contact_email}
                               onChange={(e) => setForm({...form, contact_email: e.target.value})}
                               className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm mb-4"
                               placeholder="dev@..."
                               disabled={saving}/>

                        <label className="block text-xs font-semibold text-gray-700 mb-1">Description</label>
                        <textarea value={form.app_description}
                                  onChange={(e) => setForm({...form, app_description: e.target.value})}
                                  className="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm mb-5"
                                  placeholder="Cas d'usage, volumétrie attendue, etc."
                                  rows={3}
                                  disabled={saving}/>

                        <div className="flex gap-2">
                            <button type="button" onClick={onClose} disabled={saving}
                                    className="flex-1 border border-gray-300 text-gray-700 font-semibold py-2.5 rounded-xl hover:bg-gray-50">
                                Annuler
                            </button>
                            <button type="submit" disabled={saving}
                                    className="flex-1 bg-primary-500 hover:bg-primary-600 text-white font-semibold py-2.5 rounded-xl disabled:opacity-50">
                                {saving ? 'Création…' : 'Générer la clé'}
                            </button>
                        </div>
                    </form>
                )}
            </div>
        </div>
    );
}

// ============================================================================
// CODE EXAMPLES
// ============================================================================

function CodeBlock({ children, language = 'bash' }) {
    const [copied, setCopied] = useStateApi(false);
    const copy = () => {
        navigator.clipboard.writeText(children);
        setCopied(true);
        setTimeout(() => setCopied(false), 1800);
    };
    return (
        <div className="relative bg-gray-900 rounded-xl overflow-hidden">
            <div className="flex items-center justify-between px-3 py-1.5 bg-gray-800 text-gray-400 text-[11px] uppercase tracking-wider">
                <span>{language}</span>
                <button onClick={copy} className="hover:text-white">
                    <i className={`fas ${copied ? 'fa-check' : 'fa-copy'} mr-1`}></i>
                    {copied ? 'Copié' : 'Copier'}
                </button>
            </div>
            <pre className="text-emerald-300 text-[12.5px] p-3 overflow-x-auto whitespace-pre"><code>{children}</code></pre>
        </div>
    );
}

function CodeExamples() {
    const [tab, setTab] = useStateApi('create');
    const tabs = [
        { id: 'create', label: 'Créer une course', icon: 'fa-plus' },
        { id: 'status', label: 'Statut + position', icon: 'fa-location-dot' },
        { id: 'cancel', label: 'Annuler', icon: 'fa-xmark' },
        { id: 'me',     label: 'Vérifier la clé', icon: 'fa-key' }
    ];

    const snippets = {
        create: `curl -X POST ${GATEWAY_BASE}/v1/rides \\
  -H "X-Api-Key: tbk_live_..." \\
  -H "Content-Type: application/json" \\
  -d '{
    "pickup_address":      "Gare Cornavin, Genève",
    "pickup_latitude":     46.2102,
    "pickup_longitude":    6.1426,
    "destination_address": "Aéroport, Terminal 1",
    "destination_latitude":46.2381,
    "destination_longitude":6.1090,
    "vehicle_type":        "standard",
    "guest_name":          "Jean Dupont",
    "guest_phone":         "+41791234567",
    "pickup_datetime":     "2026-04-17T10:30:00Z",
    "is_immediate":        false
  }'`,
        status: `curl ${GATEWAY_BASE}/v1/rides/booking_xxx \\
  -H "X-Api-Key: tbk_live_..."

# Réponse:
# {
#   "success": true,
#   "data": {
#     "ride_uid": "booking_xxx",
#     "status": "accepted",
#     "driver": {
#       "name": "Marc Dubois",
#       "phone": "+4179...",
#       "position": { "latitude": 46.21, "longitude": 6.14 }
#     }
#   }
# }`,
        cancel: `curl -X POST ${GATEWAY_BASE}/v1/rides/booking_xxx/cancel \\
  -H "X-Api-Key: tbk_live_..." \\
  -H "Content-Type: application/json" \\
  -d '{ "reason": "Client n\\'est plus disponible" }'`,
        me: `curl ${GATEWAY_BASE}/v1/me \\
  -H "X-Api-Key: tbk_live_..."`
    };

    return (
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden">
            <div className="px-5 py-4 border-b border-gray-100 flex items-center justify-between">
                <div>
                    <h3 className="text-base font-bold text-gray-900">Exemples d'intégration</h3>
                    <p className="text-xs text-gray-500 mt-0.5">Base URL : <code className="bg-gray-100 px-1.5 py-0.5 rounded">{GATEWAY_BASE}</code> · <a href={`${GATEWAY_BASE}/docs`} target="_blank" className="text-primary-600 hover:underline">Documentation complète</a></p>
                </div>
            </div>
            <div className="px-5 pt-3 flex gap-2 flex-wrap">
                {tabs.map(t => (
                    <button key={t.id} onClick={() => setTab(t.id)}
                            className={`px-3 py-1.5 rounded-lg text-xs font-semibold transition ${tab === t.id ? 'bg-primary-500 text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}>
                        <i className={`fas ${t.icon} mr-1.5`}></i>
                        {t.label}
                    </button>
                ))}
            </div>
            <div className="p-5">
                <CodeBlock language="bash">{snippets[tab]}</CodeBlock>
            </div>
        </div>
    );
}

// ============================================================================
// KEY ROW
// ============================================================================

function ApiKeyRow({ k, onRevoke }) {
    const status = k.status || 'pending';
    const created = k.created_at ? new Date(k.created_at + 'Z').toLocaleString('fr-CH', { dateStyle: 'short', timeStyle: 'short' }) : '-';
    const lastUsed = k.last_used_at ? new Date(k.last_used_at + 'Z').toLocaleString('fr-CH', { dateStyle: 'short', timeStyle: 'short' }) : 'Jamais';

    return (
        <div className="bg-white rounded-xl border border-gray-100 p-4 flex flex-col md:flex-row md:items-center gap-4">
            <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 flex-wrap">
                    <span className="font-semibold text-gray-900 truncate">{k.app_name}</span>
                    <ApiKeyStatusBadge status={status} />
                </div>
                {k.app_url && (
                    <a href={k.app_url} target="_blank" className="text-xs text-primary-600 hover:underline truncate block">{k.app_url}</a>
                )}
                <div className="text-xs text-gray-500 mt-1 font-mono break-all">{k.key_masked}</div>
                <div className="flex items-center gap-3 text-[11px] text-gray-400 mt-1.5 flex-wrap">
                    <span><i className="fas fa-calendar-plus mr-1"></i>Créée {created}</span>
                    <span><i className="fas fa-clock mr-1"></i>Dernier appel : {lastUsed}</span>
                    <span><i className="fas fa-bolt mr-1"></i>{k.usage_count || 0} appels</span>
                </div>
                {status === 'rejected' && k.rejection_reason && (
                    <div className="mt-2 text-xs text-rose-600 bg-rose-50 border border-rose-100 rounded px-2 py-1">
                        Refus : {k.rejection_reason}
                    </div>
                )}
            </div>
            {(status === 'pending' || status === 'active') && (
                <button onClick={() => onRevoke(k)}
                        className="border border-rose-200 text-rose-600 hover:bg-rose-50 text-sm font-semibold px-3 py-2 rounded-lg whitespace-nowrap">
                    <i className="fas fa-ban mr-1"></i>Révoquer
                </button>
            )}
        </div>
    );
}

// ============================================================================
// MAIN VIEW
// ============================================================================

const ApiView = ({ setToast }) => {
    const [keys, setKeys] = useStateApi([]);
    const [stats, setStats] = useStateApi({ total: 0, active: 0, pending: 0, revoked: 0, rejected: 0, usage_total: 0 });
    const [loading, setLoading] = useStateApi(true);
    const [showCreate, setShowCreate] = useStateApi(false);

    const load = async () => {
        setLoading(true);
        try {
            const res = await window.partnerAPI.listApiKeys();
            if (res.success) {
                setKeys(res.data?.keys || []);
                setStats(res.data?.stats || {});
            } else {
                setToast && setToast({ message: res.error || 'Erreur', type: 'error' });
            }
        } catch (e) {
            setToast && setToast({ message: e.message, type: 'error' });
        } finally {
            setLoading(false);
        }
    };

    useEffectApi(() => { load(); }, []);

    const revoke = async (k) => {
        if (!window.confirm(`Révoquer définitivement la clé "${k.app_name}" ?`)) return;
        try {
            const res = await window.partnerAPI.revokeApiKey(k.id);
            if (res.success) {
                setToast && setToast({ message: 'Clé révoquée', type: 'success' });
                load();
            } else {
                setToast && setToast({ message: res.error || 'Erreur', type: 'error' });
            }
        } catch (e) {
            setToast && setToast({ message: e.message, type: 'error' });
        }
    };

    const StatCard = ({ icon, label, value, color }) => (
        <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-4 flex items-center gap-3">
            <div className={`w-10 h-10 rounded-xl flex items-center justify-center bg-${color}-100 text-${color}-600`}>
                <i className={`fas ${icon}`}></i>
            </div>
            <div>
                <div className="text-xs text-gray-500">{label}</div>
                <div className="text-xl font-bold text-gray-900">{value}</div>
            </div>
        </div>
    );

    return (
        <div className="space-y-6">
            <div className="flex items-center justify-between flex-wrap gap-3">
                <div>
                    <h2 className="text-2xl font-bold text-gray-900 flex items-center gap-2">
                        <i className="fas fa-code text-primary-500"></i>
                        Clés API
                    </h2>
                    <p className="text-sm text-gray-500">Permettent à des applications tierces de réserver des courses via <code className="bg-gray-100 px-1.5 py-0.5 rounded text-[12px]">gateway.taxis.ch</code></p>
                </div>
                <button onClick={() => setShowCreate(true)}
                        className="bg-primary-500 hover:bg-primary-600 text-white font-semibold px-4 py-2.5 rounded-xl">
                    <i className="fas fa-plus mr-2"></i>Nouvelle clé
                </button>
            </div>

            <div className="grid grid-cols-2 md:grid-cols-5 gap-3">
                <StatCard icon="fa-key"            label="Total"        value={stats.total || 0}    color="indigo" />
                <StatCard icon="fa-circle-check"   label="Actives"      value={stats.active || 0}   color="emerald" />
                <StatCard icon="fa-hourglass-half" label="En attente"   value={stats.pending || 0}  color="amber" />
                <StatCard icon="fa-ban"            label="Révoquées"    value={stats.revoked || 0}  color="gray" />
                <StatCard icon="fa-bolt"           label="Total appels" value={stats.usage_total || 0} color="primary" />
            </div>

            <CodeExamples />

            <div className="space-y-3">
                <h3 className="text-base font-bold text-gray-900">Vos clés</h3>
                {loading ? (
                    <div className="bg-white rounded-2xl p-8 text-center text-gray-500 border border-gray-100">
                        <i className="fas fa-spinner fa-spin mr-2"></i>Chargement…
                    </div>
                ) : keys.length === 0 ? (
                    <div className="bg-white rounded-2xl p-10 text-center border border-dashed border-gray-300">
                        <i className="fas fa-key text-gray-300 text-4xl mb-3"></i>
                        <p className="text-gray-600 font-semibold">Aucune clé pour l'instant</p>
                        <p className="text-xs text-gray-400 mt-1">Créez une clé puis demandez la validation à un manager.</p>
                    </div>
                ) : (
                    keys.map(k => <ApiKeyRow key={k.id} k={k} onRevoke={revoke} />)
                )}
            </div>

            <CreateKeyModal open={showCreate} onClose={() => setShowCreate(false)} onCreated={load} setToast={setToast} />
        </div>
    );
};

window.ApiView = ApiView;
