// ActionMinutes - account-scoped team management: assign teammates to a board or the whole organization.
const { useState: useStateTm, useEffect: useEffectTm } = React;

const TM_ACCESS = [
  { v: 0, label: "Administrator" },
  { v: 1, label: "Publisher" },
  { v: 2, label: "Editor" },
  { v: 3, label: "Data Collector" },
];

function TeamPage({ navigate }) {
  const [data, setData] = useStateTm(null); // { provisioned, users, boards }
  const [err, setErr] = useStateTm(null);
  const [loading, setLoading] = useStateTm(true);
  const [form, setForm] = useStateTm({ email: "", name: "", scope: "org", boardId: "", accessType: 2 });
  const [saving, setSaving] = useStateTm(false);
  const [invited, setInvited] = useStateTm(null);
  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));

  const load = () => {
    setErr(null);
    AM_API.team
      .list()
      .then((d) => {
        setData(d);
        setLoading(false);
        if (d.boards && d.boards.length) setForm((f) => (f.boardId ? f : { ...f, boardId: d.boards[0].boardId }));
      })
      .catch((e) => {
        setErr(e.message || "Could not load the team.");
        setLoading(false);
      });
  };
  useEffectTm(() => { load(); }, []);

  const add = async () => {
    if (!form.email.trim() || saving) return;
    setSaving(true);
    setErr(null);
    try {
      await AM_API.team.add({
        email: form.email.trim(),
        name: form.name.trim() || null,
        scope: form.scope,
        boardId: form.scope === "board" ? form.boardId : null,
        accessType: Number(form.accessType),
      });
      set("email", "");
      set("name", "");
      load();
    } catch (e) {
      setErr(e.message || "Could not add the teammate.");
    } finally {
      setSaving(false);
    }
  };

  const invite = async () => {
    if (!form.email.trim() || saving) return;
    setSaving(true);
    setErr(null);
    setInvited(null);
    try {
      await AM_API.team.invite({ email: form.email.trim(), name: form.name.trim() || null });
      setInvited(form.email.trim());
      set("email", "");
      set("name", "");
      load();
    } catch (e) {
      setErr(e.message || "Could not send the invite.");
    } finally {
      setSaving(false);
    }
  };

  const remove = async (email, grant) => {
    setErr(null);
    try {
      await AM_API.team.remove(email, grant.assetType, grant.assetId);
      load();
    } catch (e) {
      setErr(e.message || "Could not remove access.");
    }
  };

  return (
    <div className="am-appmain" style={{ maxWidth: 880 }}>
      <span className="pi-eyebrow">Account</span>
      <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 22, margin: "6px 0 4px" }}>Team</h2>
      <p style={{ fontSize: 13.5, color: "var(--fg-2)", margin: "0 0 18px" }}>
        Give colleagues access to a single board or the whole organization.
      </p>

      {err && (
        <div className="am-domain-note warn" style={{ marginBottom: 14 }} role="alert">
          <span className="ico"><AMIcon name="triangle-alert" size={15} /></span>
          <span>{err}</span>
        </div>
      )}

      {loading ? (
        <div style={{ display: "flex", justifyContent: "center", minHeight: 160, alignItems: "center" }}>
          <span className="am-spin" style={{ width: 28, height: 28, borderColor: "rgba(3,149,255,0.2)", borderTopColor: "var(--pi-blue)", display: "inline-block" }}></span>
        </div>
      ) : data && data.provisioned === false ? (
        <div className="am-empty">
          <span className="ic"><AMIcon name="users" size={28} strokeWidth={1.5} /></span>
          <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, color: "var(--fg-2)", marginBottom: 4 }}>This account isn't set up yet</div>
          <p style={{ fontSize: 13, color: "var(--fg-3)" }}>Generate minutes once to set up the account, then invite teammates here.</p>
          <button className="pi-btn pi-btn-primary" style={{ marginTop: 14 }} onClick={() => navigate("/home")}>Back to dashboard</button>
        </div>
      ) : (
        <React.Fragment>
          {/* Add a teammate */}
          <div className="pi-card" style={{ padding: "20px 22px", marginBottom: 18 }}>
            <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, fontSize: 14, marginBottom: 14 }}>Add a teammate</div>

            <div className="am-two-col">
              <div className="pi-field">
                <label className="pi-field-label" htmlFor="tm-email">Email</label>
                <input id="tm-email" type="email" value={form.email} onChange={(e) => set("email", e.target.value)} placeholder="colleague@cityofalpine.gov" />
              </div>
              <div className="pi-field">
                <label className="pi-field-label" htmlFor="tm-name">Name (optional)</label>
                <input id="tm-name" type="text" value={form.name} onChange={(e) => set("name", e.target.value)} placeholder="Jordan Lee" />
              </div>
            </div>

            <div className="am-two-col" style={{ marginTop: 12 }}>
              <div className="pi-field">
                <label className="pi-field-label" htmlFor="tm-scope">Access to</label>
                <select id="tm-scope" value={form.scope} onChange={(e) => set("scope", e.target.value)}>
                  <option value="org">The whole organization</option>
                  <option value="board">A specific board</option>
                </select>
              </div>
              <div className="pi-field">
                <label className="pi-field-label" htmlFor="tm-level">Permission level</label>
                <select id="tm-level" value={form.accessType} onChange={(e) => set("accessType", e.target.value)}>
                  {TM_ACCESS.map((a) => <option key={a.v} value={a.v}>{a.label}</option>)}
                </select>
              </div>
            </div>

            {form.scope === "board" && (
              <div className="pi-field" style={{ marginTop: 12 }}>
                <label className="pi-field-label" htmlFor="tm-board">Board</label>
                <select id="tm-board" value={form.boardId} onChange={(e) => set("boardId", e.target.value)}>
                  {(data.boards || []).length === 0 && <option value="">No boards yet</option>}
                  {(data.boards || []).map((b) => (
                    <option key={b.boardId} value={b.boardId} disabled={!b.projectId}>
                      {b.name}{b.projectId ? "" : " (set up pending)"}
                    </option>
                  ))}
                </select>
              </div>
            )}

            {invited && (
              <div className="am-domain-note ok" style={{ marginTop: 14 }}>
                <span className="ico"><AMIcon name="check" size={15} /></span>
                <span>Invite sent to {invited}. They'll get an email to open the account, view its minutes, and run their own.</span>
              </div>
            )}

            <div style={{ marginTop: 16, display: "flex", gap: 8, flexWrap: "wrap" }}>
              <button className="pi-btn pi-btn-primary" onClick={invite} disabled={saving || !form.email.trim()}>
                {saving ? "Sending..." : "Send email invite"}
              </button>
              <button className="pi-btn pi-btn-outline" onClick={add} disabled={saving || !form.email.trim()}>
                {saving ? "Adding..." : "Add without emailing"}
              </button>
            </div>
          </div>

          {/* Current team */}
          {!data.users || data.users.length === 0 ? (
            <div className="am-empty">
              <span className="ic"><AMIcon name="users" size={28} strokeWidth={1.5} /></span>
              <div style={{ fontFamily: "var(--font-display)", fontWeight: 600, color: "var(--fg-2)", marginBottom: 4 }}>No teammates yet</div>
              <p style={{ fontSize: 13, color: "var(--fg-3)" }}>Add a colleague above to share this account.</p>
            </div>
          ) : (
            <div className="pi-card" style={{ padding: 0, overflow: "hidden" }} aria-live="polite">
              <table className="pi-table am-recent-table">
                <thead><tr><th>Teammate</th><th>Access</th></tr></thead>
                <tbody>
                  {data.users.map((u) => (
                    <tr key={u.adminUserId}>
                      <td>
                        <span className="pi-row-title">{u.name || u.email}</span>
                        {u.name ? <div className="pi-row-sub">{u.email}</div> : null}
                      </td>
                      <td>
                        {u.isOwner && (u.grants || []).length === 0 ? (
                          <span className="pi-badge pi-badge-success">Owner</span>
                        ) : (u.grants || []).length === 0 ? (
                          <span style={{ color: "var(--fg-3)", fontSize: 13 }}>No access</span>
                        ) : (
                          <div style={{ display: "flex", flexWrap: "wrap", gap: 6, alignItems: "center" }}>
                            {u.isOwner && <span className="pi-badge pi-badge-success">Owner</span>}
                            {u.grants.map((g, i) => (
                              <span key={i} className="pi-badge" style={{ background: "#e8f4ff", color: "var(--pi-blue)", display: "inline-flex", alignItems: "center", gap: 6 }}>
                                {g.scope === "org" ? "Whole org" : (g.boardName || "Board")} · {g.accessLabel}
                                <button
                                  type="button"
                                  aria-label={"Remove " + (u.name || u.email) + " from " + (g.scope === "org" ? "the organization" : (g.boardName || "the board"))}
                                  onClick={() => remove(u.email, g)}
                                  style={{ border: "none", background: "none", cursor: "pointer", padding: 0, lineHeight: 0, color: "inherit", display: "inline-flex" }}>
                                  <AMIcon name="x" size={12} aria-hidden="true" />
                                </button>
                              </span>
                            ))}
                          </div>
                        )}
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </React.Fragment>
      )}
    </div>
  );
}

Object.assign(window, { TeamPage });
