// Vanday — Settings → Feature flags
//
// Admin-only UI for flipping per-user feature overrides during beta. Each
// row is a user; toggle the "integrations" switch (or any future feature) to
// grant/revoke paid-tier features for that account.
//
// Backed by:
//   GET  /api/admin/users
//   POST /api/admin/users/:id/feature   { feature, enabled: bool | null }
//
// Sidebar registration: the SettingsSidebar in web/settings.jsx renders this
// item only when isAdmin is true (see the gating there).

function FeatureFlagsSection() {
  const [users, setUsers] = React.useState(null);
  const [error, setError] = React.useState(null);
  const [filter, setFilter] = React.useState("");
  const [busyKey, setBusyKey] = React.useState(null); // `${userId}:${feature}` while toggling

  const authHeaders = async () => {
    try {
      const t = window.Clerk?.session ? await window.Clerk.session.getToken() : null;
      return t ? { Authorization: `Bearer ${t}` } : {};
    } catch { return {}; }
  };

  const load = React.useCallback(async () => {
    setError(null);
    try {
      const r = await fetch("/api/admin/users", { headers: await authHeaders() });
      const body = await r.json();
      if (!r.ok) { setError(body.error || `HTTP ${r.status}`); return; }
      setUsers(body.users || []);
    } catch { setError("Couldn't reach the server."); }
  }, []);
  React.useEffect(() => { load(); }, [load]);

  const setOverride = async (userId, feature, enabled) => {
    const key = `${userId}:${feature}`;
    setBusyKey(key);
    try {
      const r = await fetch(`/api/admin/users/${encodeURIComponent(userId)}/feature`, {
        method: "POST",
        headers: { "Content-Type": "application/json", ...(await authHeaders()) },
        body: JSON.stringify({ feature, enabled }),
      });
      const body = await r.json();
      if (!r.ok) { setError(body.error || body.message || `HTTP ${r.status}`); return; }
      // Optimistic update — patch the user row in place.
      setUsers((prev) => prev.map((u) =>
        u.id === userId ? { ...u, featureOverrides: body.overrides || {} } : u,
      ));
    } catch { setError("Toggle failed — try again."); }
    finally { setBusyKey(null); }
  };

  // Features we expose toggles for. Extend as more become user-flippable.
  // Each entry is { key, label, blurb }.
  const TOGGLES = [
    {
      key: "integrations",
      label: "Integrations",
      blurb: "Connected-integrations manager UI in Settings → Integrations.",
    },
  ];

  const rows = (users || []).filter((u) => {
    if (!filter.trim()) return true;
    const q = filter.toLowerCase();
    return (u.email || "").toLowerCase().includes(q) || u.id.toLowerCase().includes(q);
  });

  return (
    <>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-end" }}>
        <div>
          <h1 className="settings-h1">Feature flags</h1>
          <p className="settings-sub">
            Toggle paid-tier features on or off for specific beta accounts.
            Overrides persist until cleared. Default state inherits from the
            user's plan / mode.
          </p>
        </div>
        <button className="btn" onClick={load}>Refresh</button>
      </div>

      {error && (
        <div style={{
          marginTop: 16, padding: 12,
          background: "oklch(0.96 0.04 24)",
          border: "1px solid oklch(0.85 0.08 24)",
          borderRadius: 8, fontSize: 13, color: "oklch(0.42 0.16 24)",
        }}>{error}</div>
      )}

      <div className="search" style={{ marginTop: 18, maxWidth: 320, background: "var(--surface-soft)" }}>
        <IcSearch size={14} />
        <input
          placeholder="Filter by email or ID…"
          value={filter}
          onChange={(e) => setFilter(e.target.value)}
        />
      </div>

      {users === null ? (
        <div style={{ marginTop: 20, color: "var(--text-faint)", fontSize: 13 }}>Loading…</div>
      ) : (
        <div className="section-card" style={{ marginTop: 18, padding: 0, overflow: "hidden" }}>
          <table className="table" style={{ width: "100%", borderCollapse: "collapse" }}>
            <thead>
              <tr>
                <th style={{ textAlign: "left" }}>User</th>
                <th style={{ textAlign: "left" }}>Plan</th>
                <th style={{ textAlign: "left" }}>Last seen</th>
                {TOGGLES.map((t) => (
                  <th key={t.key} style={{ textAlign: "center" }} title={t.blurb}>
                    {t.label}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {rows.map((u) => (
                <tr key={u.id}>
                  <td style={{ minWidth: 220 }}>
                    <div style={{ fontWeight: 500, fontSize: 13.5 }}>
                      {u.email || <span style={{ color: "var(--text-faint)" }}>(no email)</span>}
                    </div>
                    <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--text-faint)", marginTop: 2 }}>
                      {u.id}
                    </div>
                  </td>
                  <td>
                    <span className="role-pill">{u.plan || "free_beta"}</span>
                  </td>
                  <td style={{ fontFamily: "var(--font-mono)", fontSize: 11.5, color: "var(--text-muted)" }}>
                    {u.lastSeenAt
                      ? new Date(u.lastSeenAt).toLocaleDateString()
                      : <span style={{ color: "var(--text-faint)" }}>never</span>}
                  </td>
                  {TOGGLES.map((t) => {
                    const override = u.featureOverrides?.[t.key];
                    const hasOverride = override === true || override === false;
                    const on = override === true;
                    const busy = busyKey === `${u.id}:${t.key}`;
                    return (
                      <td key={t.key} style={{ textAlign: "center" }}>
                        <div style={{ display: "inline-flex", flexDirection: "column", alignItems: "center", gap: 4 }}>
                          <button
                            type="button"
                            onClick={() => setOverride(u.id, t.key, on ? false : true)}
                            disabled={busy}
                            style={{
                              width: 38, height: 22, borderRadius: 999,
                              background: on ? "var(--accent, #c8553d)" : "var(--surface-sunken)",
                              border: "1px solid " + (on ? "var(--accent, #c8553d)" : "var(--border)"),
                              position: "relative",
                              cursor: busy ? "wait" : "pointer",
                              padding: 0,
                              transition: "background 120ms",
                            }}
                            aria-label={`Toggle ${t.label} for ${u.email || u.id}`}
                          >
                            <span style={{
                              position: "absolute",
                              top: 2,
                              left: on ? 18 : 2,
                              width: 16, height: 16, borderRadius: "50%",
                              background: "white",
                              transition: "left 120ms",
                              boxShadow: "0 1px 3px rgba(0,0,0,0.2)",
                            }} />
                          </button>
                          {hasOverride ? (
                            <button
                              type="button"
                              onClick={() => setOverride(u.id, t.key, null)}
                              disabled={busy}
                              style={{
                                fontSize: 10, color: "var(--text-faint)",
                                background: "transparent", border: 0, cursor: "pointer",
                                padding: 0, textDecoration: "underline",
                              }}
                              title="Clear override — user reverts to plan default"
                            >
                              clear
                            </button>
                          ) : (
                            <span style={{ fontSize: 10, color: "var(--text-faint)" }}>
                              (default)
                            </span>
                          )}
                        </div>
                      </td>
                    );
                  })}
                </tr>
              ))}
              {rows.length === 0 && (
                <tr>
                  <td colSpan={3 + TOGGLES.length} style={{ textAlign: "center", color: "var(--text-faint)", padding: 24 }}>
                    No users match.
                  </td>
                </tr>
              )}
            </tbody>
          </table>
        </div>
      )}
    </>
  );
}

window.FeatureFlagsSection = FeatureFlagsSection;
