/* global React, Icon, Button, Badge, Backend */
// ============================================================
// Proxys — catalogue des proxys mobiles et assignation aux iPhones
// La configuration se fait ICI, une fois. Dans le pilotage, l'opérateur
// n'a plus qu'un bouton « nouvelle IP ».
// ============================================================
function AdminProxies() {
  const { useState, useEffect } = React;
  const [data, setData] = useState(null);
  const [devices, setDevices] = useState([]);
  const [editing, setEditing] = useState(null);   // fiche en cours d'édition
  const [busy, setBusy] = useState(false);

  const load = () => {
    Backend.proxyPool().then(setData);
    Backend.devices && Backend.devices().then(d => setDevices(d || [])).catch(() => {});
  };
  useEffect(() => { load(); }, []);

  const proxies = (data && data.proxies) || [];
  const assign = (data && data.assign) || {};

  const save = async (f) => {
    setBusy(true);
    const r = await Backend.proxySave(f);
    setBusy(false);
    if (r && r.error) return alert(r.error);
    setEditing(null); load();
  };
  const remove = async (p) => {
    if (!window.confirm(`Supprimer « ${p.label} » ?\n\nLes iPhones qui l'utilisent n'auront plus de proxy.`)) return;
    setBusy(true); await Backend.proxyDelete(p.id); setBusy(false); load();
  };
  const setDeviceProxy = async (udid, pid) => {
    setBusy(true); await Backend.proxyAssign(udid, pid); setBusy(false); load();
  };

  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: 1100, margin: "0 auto" }}>
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 6 }}>
        <div>
          <h1 style={{ fontSize: 18, fontWeight: 800, margin: 0 }}>Proxys</h1>
          <div style={{ fontSize: 12, color: "var(--muted)", marginTop: 4 }}>
            {proxies.length} proxy(s) · les liens et mots de passe restent sur ce Mac, jamais affichés
          </div>
        </div>
        <Button variant="primary" icon="plus" onClick={() => setEditing({})}>Nouveau proxy</Button>
      </div>

      {editing && <ProxyForm value={editing} onCancel={() => setEditing(null)} onSave={save} busy={busy} />}

      <div style={{ display: "grid", gap: 11, marginTop: 16 }}>
        {proxies.length === 0 && !editing && (
          <div style={{ ...card, textAlign: "center", color: "var(--faint)", fontSize: 12, padding: 30 }}>
            Aucun proxy.<br />Crée une fiche par proxy mobile, puis assigne-la aux iPhones concernés.
          </div>
        )}
        {proxies.map(p => (
          <div key={p.id} style={card}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
              <span style={{ width: 8, height: 8, borderRadius: 99, flex: "none",
                background: p.has_rotate ? "var(--accent)" : "var(--busy)" }} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 700 }}>{p.label}</div>
                <div className="mono" style={{ fontSize: 11, color: "var(--faint)", marginTop: 2 }}>
                  {p.host ? p.host + ":" + p.port : "hôte non renseigné"} · {p.devices} iPhone(s)
                  {p.last_rotate ? " · dernière rotation " + p.last_rotate : ""}
                </div>
              </div>
              {p.has_rotate ? <Badge tone="green">rotation prête</Badge> : <Badge tone="amber">sans lien</Badge>}
              {p.has_creds ? <Badge tone="green">IP lisible</Badge> : null}
              <Button variant="outline" onClick={() => setEditing(p)}>Modifier</Button>
              <button onClick={() => remove(p)} title="supprimer"
                style={{ background: "none", border: "1px solid var(--border)", borderRadius: 8,
                         padding: "6px 9px", color: "var(--faint)", cursor: "pointer" }}>✕</button>
            </div>
            {p.last_error && (
              <div style={{ marginTop: 8, fontSize: 11, color: "var(--danger)" }}>dernière erreur : {p.last_error}</div>
            )}
          </div>
        ))}
      </div>

      {/* assignation */}
      <div style={{ ...card, marginTop: 22 }}>
        <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".06em", textTransform: "uppercase",
                      color: "var(--muted)", marginBottom: 12 }}>Assignation aux iPhones</div>
        {devices.length === 0 ? (
          <div style={{ fontSize: 12, color: "var(--faint)" }}>Aucun iPhone détecté par le moteur.</div>
        ) : (
          <div style={{ display: "grid", gap: 8 }}>
            {devices.map(d => {
              const udid = d.udid || d.id;
              return (
                <div key={udid} style={{ display: "flex", alignItems: "center", gap: 11, padding: "9px 11px",
                  borderRadius: 10, background: "var(--surface-2)", border: "1px solid var(--border)" }}>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12, fontWeight: 600 }}>{d.label || d.name || ("iPhone-" + udid.slice(-4))}</div>
                    <div className="mono" style={{ fontSize: 10.5, color: "var(--faint)" }}>{udid}</div>
                  </div>
                  <select value={assign[udid] || ""} disabled={busy}
                    onChange={e => setDeviceProxy(udid, e.target.value)}
                    style={{ padding: "7px 10px", background: "var(--bg-2)", border: "1px solid var(--border-2)",
                             borderRadius: 8, color: "var(--text)", fontSize: 12, minWidth: 190 }}>
                    <option value="">— aucun proxy —</option>
                    {proxies.map(p => <option key={p.id} value={p.id}>{p.label}</option>)}
                  </select>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}

function ProxyForm({ value, onCancel, onSave, busy }) {
  const { useState } = React;
  const [f, setF] = useState({
    id: value.id || "", label: value.label || "", rotate_url: "",
    host: value.host || "", port: value.port || "", user: "", password: "",
  });
  const set = (k, v) => setF(x => ({ ...x, [k]: v }));
  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" };

  return (
    <div style={{ background: "var(--surface)", border: "1px solid var(--accent-line)", borderRadius: "var(--r-lg)",
                  padding: 16, marginTop: 14, display: "grid", gap: 11 }}>
      <div style={{ fontSize: 12.5, fontWeight: 700 }}>{value.id ? "Modifier le proxy" : "Nouveau proxy"}</div>
      <div>
        <label style={lab}>Nom</label>
        <input value={f.label} onChange={e => set("label", e.target.value)} placeholder="ex. Prox'Easy NY — PE-2261"
          style={{ ...box, marginTop: 3 }} />
      </div>
      <div>
        <label style={lab}>Lien de rotation</label>
        <input type="password" value={f.rotate_url} onChange={e => set("rotate_url", e.target.value)}
          placeholder={value.has_rotate ? "enregistré — laisse vide pour le garder" : "https://…"}
          style={{ ...box, marginTop: 3 }} />
        <div style={{ fontSize: 10.5, color: "var(--faint)", marginTop: 4 }}>
          Prox'Easy : fiche du proxy → « Rotation link ». C'est lui qui change l'IP.
        </div>
      </div>
      <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 2 }}>
        Identifiants de connexion — facultatifs, ils servent uniquement à <b>lire l'IP de sortie</b>
        et vérifier qu'une rotation a bien eu lieu. Renseigne le port <b>HTTP</b> même si tes
        téléphones sortent en SOCKS5 : les deux portes mènent au même tunnel, donc à la même IP.
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 9 }}>
        <div><label style={lab}>Hôte</label>
          <input value={f.host} onChange={e => set("host", e.target.value)} placeholder="b9-att-ny.proxydns.tech" style={{ ...box, marginTop: 3 }} /></div>
        <div><label style={lab}>Port HTTP</label>
          <input value={f.port} onChange={e => set("port", e.target.value)} placeholder="8416" style={{ ...box, marginTop: 3 }} />
          <div style={{ fontSize: 10, color: "var(--faint)", marginTop: 3 }}>le port HTTP, pas le SOCKS5</div></div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 9 }}>
        <div><label style={lab}>Utilisateur</label>
          <input value={f.user} onChange={e => set("user", e.target.value)} style={{ ...box, marginTop: 3 }} /></div>
        <div><label style={lab}>Mot de passe</label>
          <input type="password" value={f.password} onChange={e => set("password", e.target.value)}
            placeholder={value.has_creds ? "enregistré" : ""} style={{ ...box, marginTop: 3 }} /></div>
      </div>
      <div style={{ display: "flex", gap: 9 }}>
        <Button variant="primary" disabled={busy || !f.label.trim()} onClick={() => onSave(f)}>Enregistrer</Button>
        <Button variant="outline" onClick={onCancel}>Annuler</Button>
      </div>
    </div>
  );
}
