/* global React, Icon, Button, Badge, Backend */
// ============================================================
// API — toutes les clés des services externes, au même endroit
// Les clés restent sur ce Mac et ne sont jamais réaffichées.
// ============================================================
function AdminApiKeys() {
  const { useState, useEffect } = React;
  const [data, setData] = useState(null);
  const load = () => { Backend.apiKeys().then(setData); };
  useEffect(() => { load(); }, []);

  const services = (data && data.services) || [];
  const card = { background: "var(--surface)", border: "1px solid var(--border)",
                 borderRadius: "var(--r-lg)", padding: 16 };

  return (
    <div className="app-fade" style={{ padding: "22px 22px 40px", maxWidth: 900, margin: "0 auto" }}>
      <h1 style={{ fontSize: 18, fontWeight: 800, margin: 0 }}>API</h1>
      <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 4, marginBottom: 18 }}>
        Les services externes que la console utilise. Les clés restent sur ce Mac, ne sont
        jamais réaffichées, et tes opérateurs ne les voient pas.
      </div>

      <div style={{ display: "grid", gap: 12 }}>
        {services.map(s => <ApiCard key={s.id} s={s} onSaved={load} card={card} />)}
        {services.length === 0 && (
          <div style={{ ...card, color: "var(--faint)", fontSize: 12, textAlign: "center", padding: 28 }}>
            Chargement…
          </div>
        )}
      </div>
    </div>
  );
}

function ApiCard({ s, onSaved, card }) {
  const { useState } = React;
  const [vals, setVals] = useState(() => {
    const o = {}; (s.fields || []).forEach(f => { o[f.id] = f.secret ? "" : (f.value || ""); }); return o;
  });
  const [busy, setBusy] = useState(false);
  const [msg, setMsg] = useState(null);
  const [open, setOpen] = useState(!s.configured);

  const save = async () => {
    setBusy(true);
    await Backend.apiKeysSave(s.id, vals);
    setBusy(false);
    (s.fields || []).forEach(f => { if (f.secret) setVals(v => ({ ...v, [f.id]: "" })); });
    setMsg("Enregistré."); setTimeout(() => setMsg(null), 3500);
    onSaved && onSaved();
  };
  const clear = async () => {
    if (!window.confirm(`Retirer la clé ${s.name} ?`)) return;
    const empty = {}; (s.fields || []).forEach(f => { if (f.secret) empty[f.id] = ""; });
    setBusy(true); await Backend.apiKeysSave(s.id, empty); setBusy(false); onSaved && onSaved();
  };

  const box = { width: "100%", padding: "9px 11px", background: "var(--bg-2)",
                border: "1px solid var(--border-2)", borderRadius: 9, color: "var(--text)",
                fontSize: 12, outline: "none" };
  const lab = { fontSize: 10.5, fontWeight: 600, color: "var(--faint)",
                textTransform: "uppercase", letterSpacing: ".05em" };

  const check = s.check;
  return (
    <div style={card}>
      <div onClick={() => setOpen(o => !o)} style={{ display: "flex", alignItems: "center", gap: 11, cursor: "pointer" }}>
        <span style={{ display: "grid", color: "var(--faint)", transform: open ? "none" : "rotate(-90deg)", transition: "transform .16s" }}>
          {React.createElement(Icon.chevDown, { size: 15 })}
        </span>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 700 }}>{s.name}</div>
          <div style={{ fontSize: 11, color: "var(--faint)", marginTop: 2 }}>{s.category} · {s.help}</div>
        </div>
        {check && check.ok ? <Badge tone="green">solde {check.balance} $</Badge>
          : check && !check.ok ? <Badge tone="red">clé refusée</Badge>
          : s.configured ? <Badge tone="green">configuré</Badge>
          : <Badge tone="amber">à configurer</Badge>}
      </div>

      {open && (
        <div style={{ marginTop: 14, display: "grid", gap: 10 }}>
          {s.where && (
            <div style={{ fontSize: 11, color: "var(--muted)" }}>
              Où la trouver : {s.where}
              {s.url ? <> · <a href={s.url} target="_blank" rel="noreferrer" style={{ color: "var(--accent)" }}>{s.url.replace(/^https?:\/\//, "")}</a></> : null}
            </div>
          )}
          {(s.fields || []).map(f => (
            <div key={f.id}>
              <label style={lab}>{f.label}{f.optional ? " (facultatif)" : ""}</label>
              {f.choices_from
                ? <ChoiceField field={f} value={vals[f.id] || ""} box={box}
                    onChange={v => setVals(x => ({ ...x, [f.id]: v }))} />
                : <input type={f.secret ? "password" : "text"} value={vals[f.id] || ""}
                    onChange={e => setVals(v => ({ ...v, [f.id]: e.target.value }))}
                    placeholder={f.filled && f.secret ? "enregistrée — laisse vide pour la garder" : (f.placeholder || "")}
                    style={{ ...box, marginTop: 3 }} />}
            </div>
          ))}
          {check && !check.ok && (
            <div style={{ fontSize: 11, color: "var(--danger)" }}>{s.name} : {check.error}</div>
          )}
          <div style={{ display: "flex", gap: 9, alignItems: "center" }}>
            <Button variant="primary" disabled={busy} onClick={save}>Enregistrer</Button>
            {s.configured && (
              <button onClick={clear} style={{ background: "none", border: "none", color: "var(--faint)",
                fontSize: 11, cursor: "pointer" }}>retirer la clé</button>
            )}
            {msg && <span style={{ fontSize: 11.5, color: "var(--accent)" }}>{msg}</span>}
          </div>
        </div>
      )}
    </div>
  );
}

// Liste déroulante alimentée par le service lui-même : les noms d'API ne sont pas
// devinables (« Instagram / Threads » s'appelle `instagram/threads`), et le prix + le stock
// aident à choisir.
function ChoiceField({ field, value, onChange, box }) {
  const { useState, useEffect } = React;
  const [opts, setOpts] = useState(null);
  const [q, setQ] = useState("");
  useEffect(() => {
    let on = true;
    Backend.smsServices().then(r => { if (on) setOpts(r && r.ok ? r.services : []); });
    return () => { on = false; };
  }, []);

  if (opts === null) return <div style={{ ...box, marginTop: 3, color: "var(--faint)" }}>chargement des services…</div>;
  if (!opts.length) return (
    <input value={value} onChange={e => onChange(e.target.value)} placeholder={field.placeholder}
      style={{ ...box, marginTop: 3 }} />
  );
  const filtered = q ? opts.filter(o => (o.name + " " + o.api_name).toLowerCase().includes(q.toLowerCase())) : opts;
  return (
    <div style={{ display: "grid", gap: 6, marginTop: 3 }}>
      <input value={q} onChange={e => setQ(e.target.value)} placeholder="filtrer (instagram, google…)"
        style={{ ...box, fontSize: 11.5 }} />
      <select value={value} onChange={e => onChange(e.target.value)} style={{ ...box }}>
        <option value="">— choisir un service —</option>
        {filtered.slice(0, 120).map(o => (
          <option key={o.api_name} value={o.api_name}>
            {o.name} — {o.price} $ · stock {o.stock}
          </option>
        ))}
      </select>
    </div>
  );
}
