/* Admin surface — invitations + share-links + a small ops glance.
   Renders inside the workspace shell. Only accessible when /me reports
   is_admin: true (App enforces the visibility).
*/

const { useState: useAS, useEffect: useAE } = React;

function ViewAdminInvites() {
  const [rows, setRows]         = useAS([]);
  const [name, setName]         = useAS("");
  const [email, setEmail]       = useAS("");
  const [busy, setBusy]         = useAS(false);
  const [err, setErr]           = useAS("");
  const [link, setLink]         = useAS("");

  async function refresh() {
    const r = await Api.adminInvites();
    if (r.ok) setRows((r.data && r.data.invites) || []);
  }
  useAE(() => { refresh(); }, []);

  async function mint(e) {
    e.preventDefault();
    setBusy(true); setErr(""); setLink("");
    const r = await Api.mintInvite({ name: name.trim(), email: email.trim() });
    setBusy(false);
    if (!r.ok) {
      setErr(r.status === 409 ? "An invite already exists for that email." : "Couldn't mint the invite.");
      return;
    }
    setLink((r.data && r.data.url) || "");
    setName(""); setEmail("");
    refresh();
  }

  async function revoke(token) {
    if (!confirm("Revoke this invite?")) return;
    const r = await Api.revokeInvite(token);
    if (r.ok) refresh();
  }
  async function resetUsage(token) {
    const r = await Api.resetInviteUsage(token);
    if (r.ok) refresh();
  }

  return (
    <div className="surface-pad">
      <h1>Admin</h1>
      <p className="sub">Invitations, share-links, ops</p>

      <div className="admin-card">
        <div className="admin-card-head">
          <h2>Mint an invitation</h2>
        </div>
        <div className="admin-card-body">
          <form onSubmit={mint} className="auth-form" style={{ flexDirection: "row", alignItems: "flex-end", gap: 12 }}>
            <label className="auth-field" style={{ flex: 1 }}>
              <span className="auth-field-label">Name</span>
              <input value={name} onChange={(e) => setName(e.target.value)} required maxLength={120}/>
            </label>
            <label className="auth-field" style={{ flex: 1 }}>
              <span className="auth-field-label">Email</span>
              <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} required maxLength={200}/>
            </label>
            <button className="btn primary" disabled={busy}>{busy ? "Minting…" : "Mint"}</button>
          </form>
          {err  && <p className="auth-status is-miss" style={{ marginTop: 10 }}>{err}</p>}
          {link && (
            <p className="auth-status is-ok" style={{ marginTop: 10 }}>
              Invite ready — copy this URL: <span className="mono">{link}</span>
            </p>
          )}
        </div>
      </div>

      <div className="admin-card">
        <div className="admin-card-head">
          <h2>Active invitees ({rows.length})</h2>
          <button className="btn ghost" onClick={refresh}>Refresh</button>
        </div>
        <div className="admin-card-body" style={{ padding: 0 }}>
          <table className="admin-table">
            <thead>
              <tr>
                <th>Name</th><th>Email</th><th>Uses</th><th>Last used</th><th>State</th><th></th>
              </tr>
            </thead>
            <tbody>
              {rows.map((r) => (
                <tr key={r.token}>
                  <td>{r.name}</td>
                  <td className="mono">{r.email}</td>
                  <td className="num">{r.uses || 0}</td>
                  <td className="mono" style={{ color: "var(--ink-3)" }}>{r.last_used_at ? r.last_used_at.slice(0, 16).replace("T", " ") : "—"}</td>
                  <td>
                    <span className={`pill ${r.disabled ? "miss" : "ok"}`}>
                      <span className={`vdot ${r.disabled ? "miss" : "ok"}`}/>
                      {r.disabled ? "disabled" : "active"}
                    </span>
                  </td>
                  <td style={{ textAlign: "right" }}>
                    <button className="btn sm ghost" onClick={() => resetUsage(r.token)}>Reset uses</button>{" "}
                    <button className="btn sm ghost" onClick={() => revoke(r.token)} style={{ color: "var(--miss)" }}>Revoke</button>
                  </td>
                </tr>
              ))}
              {!rows.length && <tr><td colSpan={6} style={{ color: "var(--ink-3)" }}>No invitations yet.</td></tr>}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ViewAdminInvites });
