/* NGIPL PLM: Admin tab (users and password reset). Shown to admin accounts only. */
function AdminView({ toast }) {
  const [users, setUsers] = React.useState(null);
  const [err, setErr] = React.useState("");
  const [loading, setLoading] = React.useState(false);
  const [resetFor, setResetFor] = React.useState(null);
  const api = window.PLM_CLOUD_API;
  const admins = ((window.PLM_CONFIG && window.PLM_CONFIG.adminEmails) || []).map((e) => String(e).toLowerCase().trim());
  const me = (PLM.get().settings.editor || "").toLowerCase();

  function load() {
    if (!api) { setErr("User management needs the cloud version of the app."); return; }
    setLoading(true); setErr("");
    api.listUsers()
      .then((rows) => setUsers(rows || []))
      .catch((e) => setErr(e.message))
      .then(() => setLoading(false));
  }
  React.useEffect(load, []);

  function fmtWhen(ts) { return ts ? PLM.fmtDate(new Date(ts).getTime()) : "Never"; }

  return (
    <div data-screen-label="Admin">
      <div className="toolbar">
        <div className="f-label" style={{ margin: 0, fontSize: 12 }}>Users</div>
        <span className="caption">{users ? users.length + " account" + (users.length === 1 ? "" : "s") : ""}</span>
        <div className="spacer"></div>
        <Btn variant="secondary" size="sm" disabled={loading} onClick={load}>{loading ? "Loading…" : "Refresh"}</Btn>
      </div>

      {err ? <div className="panel" style={{ padding: 16, color: "var(--red-700)", marginBottom: 12 }}>{err}</div> : null}

      <div className="panel panel--strong plm-table-wrap">
        <table className="plm-table admin-users">
          <thead>
            <tr>
              <th>Email</th>
              <th className="col-unit" style={{ width: 170 }}>Created</th>
              <th className="col-unit" style={{ width: 170 }}>Last sign in</th>
              <th style={{ width: 150 }} className="admin-act"></th>
            </tr>
          </thead>
          <tbody>
            {(users || []).map((u) => {
              const isAdmin = admins.indexOf(String(u.email || "").toLowerCase()) !== -1;
              return (
                <tr key={u.id}>
                  <td>
                    <div style={{ overflowWrap: "anywhere" }}>{u.email}</div>
                    <div className="caption" style={{ marginTop: 2 }}>
                      {isAdmin ? "Admin" : "User"}{String(u.email || "").toLowerCase() === me ? " · you" : ""}
                    </div>
                    <div className="row-meta">Last sign in {fmtWhen(u.last_sign_in_at)}</div>
                  </td>
                  <td className="col-unit caption">{fmtWhen(u.created_at)}</td>
                  <td className="col-unit caption">{fmtWhen(u.last_sign_in_at)}</td>
                  <td style={{ textAlign: "right" }}>
                    <Btn variant="secondary" size="sm" onClick={() => setResetFor(u)}><span className="tab-full">Reset password</span><span className="tab-short">Reset</span></Btn>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        {users && !users.length ? <div className="caption" style={{ padding: 24, textAlign: "center" }}>No accounts found.</div> : null}
        {!users && !err ? <div className="caption" style={{ padding: 24, textAlign: "center" }}>Loading users…</div> : null}
      </div>
      <div className="caption" style={{ marginTop: 10 }}>
        New accounts are still added in the Supabase dashboard (Authentication, Users). A reset takes effect at the user's next sign in.
      </div>

      {resetFor ? <ResetPasswordDialog user={resetFor} onClose={() => setResetFor(null)} toast={toast}></ResetPasswordDialog> : null}
    </div>
  );
}

function ResetPasswordDialog({ user, onClose, toast }) {
  const [p1, setP1] = React.useState("");
  const [p2, setP2] = React.useState("");
  const [show, setShow] = React.useState(false);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState("");
  const tooShort = p1.length > 0 && p1.length < 6;
  const mismatch = p2.length > 0 && p1 !== p2;
  const canSave = p1.length >= 6 && p1 === p2 && !busy;

  function save() {
    setBusy(true); setErr("");
    window.PLM_CLOUD_API.setPassword(user.id, p1)
      .then(() => { toast("Password reset for " + user.email); onClose(); })
      .catch((e) => { setErr(e.message); setBusy(false); });
  }

  return (
    <Dialog title="Reset password" onClose={onClose} width={460}
      footer={
        <React.Fragment>
          <Btn variant="ghost" size="sm" onClick={onClose}>Cancel</Btn>
          <Btn size="sm" disabled={!canSave} onClick={save}>{busy ? "Saving…" : "Set new password"}</Btn>
        </React.Fragment>
      }>
      <div className="f-stack">
        <div className="caption">New password for <strong style={{ color: "var(--text-display)" }}>{user.email}</strong>. Pass it on to them yourself, nothing is emailed.</div>
        <Field label="New password (minimum 6 characters)">
          <input className="f-input" type={show ? "text" : "password"} autoComplete="new-password" value={p1} onChange={(e) => setP1(e.target.value)} />
        </Field>
        <Field label="Type it again">
          <input className="f-input" type={show ? "text" : "password"} autoComplete="new-password" value={p2} onChange={(e) => setP2(e.target.value)}
            onKeyDown={(e) => { if (e.key === "Enter" && canSave) save(); }} />
        </Field>
        <label className="caption" style={{ display: "inline-flex", alignItems: "center", gap: 8, cursor: "pointer" }}>
          <input type="checkbox" checked={show} onChange={(e) => setShow(e.target.checked)} /> Show password
        </label>
        {tooShort ? <div className="caption" style={{ color: "var(--red-700)" }}>Too short, at least 6 characters.</div> : null}
        {mismatch ? <div className="caption" style={{ color: "var(--red-700)" }}>The two entries do not match.</div> : null}
        {err ? <div className="caption" style={{ color: "var(--red-700)" }}>{err}</div> : null}
      </div>
    </Dialog>
  );
}

Object.assign(window, { AdminView });
