// Aria console — amministrazione piattaforma (solo platform admin): catalogo
// utenti con i flag di piattaforma. Il flag "amministratore" e il limite di
// organizzazioni possedute (0 = nessuna, vuoto/illimitato = nessun limite)
// si modificano inline; l'enforcement vero è server-side (verifica live).
const { Card, Badge, Banner, Button, Icon, IconButton, Switch, TextField, Avatar, Dialog } = window.AriaDesignSystem_af77ab;

function UserRow({ u, self, onPatch }) {
  const unlimited = u.maxOwnedOrgs == null;
  // Bozza locale del limite: si applica su blur/invio, non a ogni tasto.
  const [limit, setLimit] = React.useState(unlimited ? "" : String(u.maxOwnedOrgs));
  React.useEffect(() => { setLimit(unlimited ? "" : String(u.maxOwnedOrgs)); }, [u.maxOwnedOrgs]);

  function commitLimit() {
    if (unlimited) return;
    const n = parseInt(limit, 10);
    if (Number.isNaN(n) || n < 0) { setLimit(String(u.maxOwnedOrgs)); return; }
    if (n !== u.maxOwnedOrgs) onPatch(u, { maxOwnedOrgs: n });
  }

  return (
    <div style={{ display: "flex", alignItems: "center", gap: 14, padding: "12px 2px", borderBottom: "1px solid var(--border-subtle)" }}>
      <Avatar name={u.displayName || u.username} tone={self ? "sky" : "sage"} />
      <span style={{ display: "flex", flexDirection: "column", lineHeight: 1.25, flex: 1, minWidth: 0 }}>
        <span style={{ fontSize: 13.5, fontWeight: 500, color: "var(--text-strong)" }}>
          {u.displayName || u.username} {self && <span style={{ color: "var(--text-subtle)", fontWeight: 400 }}>(tu)</span>}
        </span>
        <span style={{ fontSize: 12, color: "var(--text-subtle)" }}>{u.username} · {u.ownedOrgs} org possedute</span>
      </span>

      {/* Limite organizzazioni: interruttore illimitato + valore puntuale. */}
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <Switch checked={unlimited} label="Illimitate"
          onChange={(e) => onPatch(u, { maxOwnedOrgs: e.target.checked ? null : (u.ownedOrgs || 0) })} />
        {!unlimited && (
          <span style={{ width: 74 }}>
            <TextField value={limit}
              onChange={(e) => setLimit(e.target.value)}
              onBlur={commitLimit}
              onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); commitLimit(); } }} />
          </span>
        )}
      </div>

      <div style={{ width: 170, display: "flex", justifyContent: "flex-end" }}>
        {self ? (
          <Badge tone="accent">Amministratore</Badge>
        ) : (
          <Switch checked={u.platformAdmin} label="Admin sistema"
            onChange={(e) => onPatch(u, { platformAdmin: e.target.checked })} />
        )}
      </div>
    </div>
  );
}

// Invito di piattaforma: crea un account che potrà FONDARE le proprie
// organizzazioni (capienza scelta qui). L'esito mostra il link copiabile —
// senza SMTP la consegna è a carico dell'amministratore.
function PlatformInviteDialog({ onClose, onCreated, notify }) {
  const [email, setEmail] = React.useState("");
  const [unlimited, setUnlimited] = React.useState(false);
  const [limit, setLimit] = React.useState("1");
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [created, setCreated] = React.useState(null); // { link, email, emailSent }

  async function submit(e) {
    if (e) e.preventDefault();
    setError(null); setBusy(true);
    try {
      const grant = unlimited ? null : Math.max(0, parseInt(limit, 10) || 0);
      const res = await window.AriaData.createPlatformInvite(email.trim(), grant);
      if (res.ok) {
        setCreated({ link: window.location.origin + res.invitePath, email: res.email, emailSent: res.emailSent });
        onCreated();
      } else {
        setError(res.error);
      }
    } finally { setBusy(false); }
  }

  async function copyLink() {
    try {
      await navigator.clipboard.writeText(created.link);
      notify({ tone: "success", title: "Link copiato", body: created.email });
    } catch (_e) {
      notify({ tone: "danger", title: "Copia non riuscita", body: "Seleziona e copia il link a mano." });
    }
  }

  return (
    <Dialog open onClose={() => (busy ? null : onClose())} title="Invita un utente sulla piattaforma"
      footer={created ? (
        <Button variant="primary" onClick={onClose}>Chiudi</Button>
      ) : (
        <React.Fragment>
          <Button variant="secondary" disabled={busy} onClick={onClose}>Annulla</Button>
          <Button variant="primary" disabled={busy || email.trim() === ""}
            iconLeft={busy ? <Icon name="loader" size={16} color="#fff" /> : <Icon name="mail-plus" size={16} color="#fff" />}
            onClick={submit}>Invita</Button>
        </React.Fragment>
      )}>
      <div style={{ display: "flex", flexDirection: "column", gap: 14, minWidth: 380 }}>
        {created ? (
          <React.Fragment>
            <Banner tone="success" title="Invito creato" icon="check-circle-2">
              {created.emailSent
                ? `Email inviata a ${created.email}. Il link resta valido comunque:`
                : `Consegna tu il link a ${created.email} (nessun SMTP configurato):`}
            </Banner>
            <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
              <code style={{ flex: 1, fontSize: 11.5, padding: "8px 10px", background: "var(--surface-app)", border: "1px solid var(--border-subtle)", borderRadius: "var(--radius-sm)", overflowWrap: "anywhere" }}>{created.link}</code>
              <Button variant="secondary" size="sm" iconLeft={<Icon name="copy" size={14} />} onClick={copyLink}>Copia</Button>
            </div>
          </React.Fragment>
        ) : (
          <React.Fragment>
            <span style={{ fontSize: 13, color: "var(--text-muted)" }}>
              L'invitato si registra e può <b>creare le sue organizzazioni</b> (fino alla capienza scelta), senza entrare in nessuna delle tue.
            </span>
            {error && <Banner tone="danger" icon="alert-circle">{error}</Banner>}
            <TextField label="Email" required value={email} placeholder="persona@azienda.it" onChange={(e) => setEmail(e.target.value)} />
            <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
              <Switch checked={unlimited} label="Organizzazioni illimitate" onChange={(e) => setUnlimited(e.target.checked)} />
              {!unlimited && (
                <span style={{ width: 90 }}>
                  <TextField label="Capienza" value={limit} onChange={(e) => setLimit(e.target.value)} />
                </span>
              )}
            </div>
          </React.Fragment>
        )}
      </div>
    </Dialog>
  );
}

function UsersAdmin({ notify }) {
  const { user } = window.AriaAuth.useAuth();
  const [users, setUsers] = React.useState(null); // null = caricamento
  const [error, setError] = React.useState(null);
  const [reloadKey, setReloadKey] = React.useState(0);
  const [invites, setInvites] = React.useState(null); // inviti di piattaforma pendenti
  const [inviting, setInviting] = React.useState(false);

  React.useEffect(() => {
    let alive = true;
    setError(null);
    window.AriaData.getUsers().then(
      (list) => { if (alive) setUsers(list); },
      (err) => { if (alive) setError(err); }
    );
    window.AriaData.listPlatformInvites().then(
      (list) => { if (alive) setInvites(list); },
      () => { /* accessorio: la lista utenti resta usabile */ }
    );
    return () => { alive = false; };
  }, [reloadKey]);

  async function revokeInvite(inv) {
    const res = await window.AriaData.revokePlatformInvite(inv.id);
    if (res.ok) notify({ tone: "success", title: "Invito revocato", body: inv.email });
    else notify({ tone: "danger", title: "Revoca non riuscita", body: res.error });
    setReloadKey((k) => k + 1);
  }

  async function patch(target, body) {
    const res = await window.AriaData.updateUserFlags(target.id, body);
    if (res.ok) {
      notify({ tone: "success", title: "Utente aggiornato", body: target.username });
    } else {
      notify({ tone: "danger", title: "Aggiornamento non riuscito", body: res.error });
    }
    setReloadKey((k) => k + 1);
  }

  if (error) {
    return (
      <div style={{ padding: 28 }}>
        <Banner tone="danger" title="Impossibile caricare gli utenti" icon="alert-circle">
          <span>{error.message || "Errore inatteso."} </span>
          <Button variant="ghost" size="sm" onClick={() => setReloadKey((k) => k + 1)}>Riprova</Button>
        </Banner>
      </div>
    );
  }
  if (users == null) {
    return (
      <div style={{ flex: 1, display: "flex", alignItems: "center", justifyContent: "center", gap: 10, color: "var(--text-muted)", padding: 40 }}>
        <Icon name="loader" size={22} color="var(--text-subtle)" />
        <span style={{ fontSize: 14 }}>Caricamento utenti…</span>
      </div>
    );
  }

  return (
    <div style={{ padding: 24, display: "flex", flexDirection: "column", gap: 18, maxWidth: 860 }}>
      <Card>
        <div style={{ padding: "16px 18px", display: "flex", flexDirection: "column", gap: 10 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
            <div style={{ display: "flex", flexDirection: "column", gap: 2, flex: 1 }}>
              <span style={{ font: "var(--fw-semibold) 15px/1.3 var(--font-sans)", color: "var(--text-strong)" }}>Utenti della piattaforma ({users.length})</span>
              <span style={{ fontSize: 12, color: "var(--text-muted)" }}>
                Il limite governa quante organizzazioni un utente può possedere (crearne una o riceverne la ownership). Gli amministratori di sistema non hanno limiti.
              </span>
            </div>
            <Button variant="primary" size="sm" iconLeft={<Icon name="mail-plus" size={15} color="#fff" />} onClick={() => setInviting(true)}>Invita utente</Button>
            <IconButton label="Ricarica" onClick={() => setReloadKey((k) => k + 1)}><Icon name="refresh-cw" size={15} /></IconButton>
          </div>
          <div style={{ display: "flex", flexDirection: "column" }}>
            {users.map((u) => (
              <UserRow key={u.id} u={u} self={user && u.id === user.id} onPatch={patch} />
            ))}
          </div>
        </div>
      </Card>

      {/* --- Inviti di piattaforma pendenti --------------------------------- */}
      {invites != null && invites.length > 0 && (
        <Card>
          <div style={{ padding: "16px 18px", display: "flex", flexDirection: "column", gap: 10 }}>
            <span style={{ font: "var(--fw-semibold) 15px/1.3 var(--font-sans)", color: "var(--text-strong)" }}>Inviti in attesa ({invites.length})</span>
            <div style={{ display: "flex", flexDirection: "column" }}>
              {invites.map((inv) => (
                <div key={inv.id} style={{ display: "flex", alignItems: "center", gap: 12, padding: "10px 2px", borderBottom: "1px solid var(--border-subtle)" }}>
                  <Icon name="mail" size={16} color="var(--text-subtle)" />
                  <span style={{ display: "flex", flexDirection: "column", lineHeight: 1.25, flex: 1, minWidth: 0 }}>
                    <span style={{ fontSize: 13.5, color: "var(--text-strong)" }}>{inv.email}</span>
                    <span style={{ fontSize: 12, color: "var(--text-subtle)" }}>
                      invitato da {inv.invitedByUsername} · capienza {inv.grantMaxOwnedOrgs == null ? "illimitata" : inv.grantMaxOwnedOrgs} · scade {new Date(inv.expiresAt).toLocaleDateString("it-IT")}
                    </span>
                  </span>
                  {inv.expired && <Badge tone="danger">scaduto</Badge>}
                  <IconButton label="Revoca invito" onClick={() => revokeInvite(inv)}><Icon name="trash-2" size={15} /></IconButton>
                </div>
              ))}
            </div>
          </div>
        </Card>
      )}

      {inviting && (
        <PlatformInviteDialog notify={notify}
          onClose={() => setInviting(false)}
          onCreated={() => setReloadKey((k) => k + 1)} />
      )}
    </div>
  );
}

Object.assign(window, { UsersAdmin });
