/* CRM Users — Admin-only user management view */
const { useState: useUsr, useEffect: useUef, useCallback: useUcb } = React;

// ─── Role badge ───────────────────────────────────────────────────────────────
function RoleBadge({ role }) {
  const styles = {
    admin:  { background: "var(--accent)",   color: "var(--paper)", border: "none" },
    editor: { background: "transparent",      color: "var(--ink)",   border: "1px solid var(--rule)" },
    viewer: { background: "var(--surface-2)", color: "var(--fog)",   border: "1px solid var(--rule-soft)" },
  };
  const s = styles[role] || styles.viewer;
  return (
    <span style={{
      ...s, borderRadius: 1, padding: "2px 8px",
      fontFamily: "var(--font-mono)", fontSize: 9,
      letterSpacing: "0.14em", textTransform: "uppercase",
    }}>
      {role}
    </span>
  );
}

// ─── Status dot ───────────────────────────────────────────────────────────────
function StatusDot({ active }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}>
      <span style={{
        width: 6, height: 6, borderRadius: "50%",
        background: active ? "var(--accent)" : "var(--fog)",
        display: "inline-block",
      }} />
      <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: active ? "var(--ink)" : "var(--fog)" }}>
        {active ? "Active" : "Disabled"}
      </span>
    </span>
  );
}

// ─── New user modal ───────────────────────────────────────────────────────────
function NewUserModal({ onClose, onCreated }) {
  const [form, setForm]   = useUsr({ username: "", email: "", password: "", role: "viewer" });
  const [error, setError] = useUsr("");
  const [saving, setSaving] = useUsr(false);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError("");
    setSaving(true);
    try {
      const res = await fetch("/api/users/", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });
      const data = await res.json();
      if (res.ok) {
        onCreated(data);
        onClose();
      } else {
        setError(data.error || "Failed to create user.");
      }
    } catch (_) {
      setError("Network error — check connection.");
    } finally {
      setSaving(false);
    }
  };

  const inp = {
    style: {
      width: "100%", background: "var(--surface)", border: "1px solid var(--rule)",
      borderRadius: 1, padding: "8px 10px", color: "var(--ink)",
      fontFamily: "var(--font-mono)", fontSize: 12, outline: "none",
      boxSizing: "border-box",
    }
  };
  const lbl = {
    style: {
      display: "block", fontFamily: "var(--font-mono)", fontSize: 9,
      letterSpacing: "0.14em", textTransform: "uppercase",
      color: "var(--fog)", marginBottom: 6,
    }
  };

  return (
    <div style={{
      position: "fixed", inset: 0, zIndex: 9000,
      background: "rgba(0,0,0,0.55)", display: "flex",
      alignItems: "center", justifyContent: "center",
    }} onClick={e => e.target === e.currentTarget && onClose()}>
      <div style={{
        width: 380, background: "var(--surface)",
        border: "1px solid var(--rule)", borderRadius: 2, padding: "28px 28px 24px",
      }}>
        <div style={{
          fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.18em",
          textTransform: "uppercase", color: "var(--fog)", marginBottom: 20,
        }}>
          § Users / New
        </div>
        <form onSubmit={handleSubmit}>
          <div style={{ marginBottom: 14 }}>
            <label {...lbl}>Username</label>
            <input {...inp} value={form.username} onChange={e => set("username", e.target.value)}
              autoFocus required placeholder="e.g. jane" />
          </div>
          <div style={{ marginBottom: 14 }}>
            <label {...lbl}>Email</label>
            <input {...inp} type="email" value={form.email} onChange={e => set("email", e.target.value)}
              placeholder="jane@example.com" />
          </div>
          <div style={{ marginBottom: 14 }}>
            <label {...lbl}>Password</label>
            <input {...inp} type="password" value={form.password}
              onChange={e => set("password", e.target.value)} required placeholder="Set initial password" />
          </div>
          <div style={{ marginBottom: 24 }}>
            <label {...lbl}>Role</label>
            <select {...inp} value={form.role} onChange={e => set("role", e.target.value)}>
              <option value="viewer">Viewer — read-only</option>
              <option value="editor">Editor — create & update</option>
              <option value="admin">Admin — full access</option>
            </select>
          </div>

          {error && (
            <div style={{
              marginBottom: 16, padding: "8px 10px",
              background: "rgba(220,50,50,0.08)", border: "1px solid rgba(220,50,50,0.3)",
              borderRadius: 1, fontFamily: "var(--font-mono)", fontSize: 10, color: "#e05555",
            }}>
              {error}
            </div>
          )}

          <div style={{ display: "flex", gap: 10 }}>
            <button type="submit" disabled={saving} style={{
              flex: 1, padding: "9px 0",
              background: saving ? "var(--fog)" : "var(--accent)",
              border: "none", borderRadius: 1, cursor: saving ? "wait" : "pointer",
              fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.12em",
              textTransform: "uppercase", color: "var(--paper)",
            }}>
              {saving ? "Creating…" : "Create user →"}
            </button>
            <button type="button" onClick={onClose} style={{
              padding: "9px 18px", background: "none",
              border: "1px solid var(--rule)", borderRadius: 1, cursor: "pointer",
              fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.12em",
              textTransform: "uppercase", color: "var(--fog)",
            }}>
              Cancel
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ─── Row actions dropdown ─────────────────────────────────────────────────────
function RowActions({ user, currentUserId, onUpdate, onDelete }) {
  const [open, setOpen]   = useUsr(false);
  const [busy, setBusy]   = useUsr(false);

  const patch = async (payload) => {
    setBusy(true);
    setOpen(false);
    try {
      const res = await fetch(`/api/users/${user.id}/`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      if (res.ok) onUpdate(await res.json());
    } catch (_) {}
    setBusy(false);
  };

  const del = async () => {
    if (!confirm(`Delete user "${user.username}"? This cannot be undone.`)) return;
    setBusy(true);
    setOpen(false);
    try {
      const res = await fetch(`/api/users/${user.id}/`, { method: "DELETE" });
      if (res.ok) onDelete(user.id);
    } catch (_) {}
    setBusy(false);
  };

  const isSelf = user.id === currentUserId;

  const menuItem = (label, onClick, danger) => (
    <button onClick={onClick} style={{
      display: "block", width: "100%", padding: "7px 14px", border: "none",
      background: "none", cursor: "pointer", textAlign: "left",
      fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.1em",
      textTransform: "uppercase", color: danger ? "#e05555" : "var(--ink)",
    }}
    onMouseEnter={e => e.target.style.background = "var(--surface-2)"}
    onMouseLeave={e => e.target.style.background = "none"}
    >
      {label}
    </button>
  );

  const roles = ["admin", "editor", "viewer"].filter(r => r !== user.role);

  return (
    <div style={{ position: "relative" }}>
      <button onClick={() => setOpen(o => !o)} disabled={busy} style={{
        background: "none", border: "1px solid var(--rule-soft)",
        borderRadius: 1, padding: "3px 10px", cursor: "pointer",
        fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.12em",
        textTransform: "uppercase", color: "var(--fog)",
      }}>
        {busy ? "…" : "···"}
      </button>

      {open && (
        <>
          <div style={{ position: "fixed", inset: 0, zIndex: 100 }} onClick={() => setOpen(false)} />
          <div style={{
            position: "absolute", right: 0, top: "calc(100% + 4px)", zIndex: 200,
            background: "var(--surface)", border: "1px solid var(--rule)",
            borderRadius: 2, minWidth: 180, overflow: "hidden",
            boxShadow: "0 4px 16px rgba(0,0,0,0.3)",
          }}>
            {/* Toggle active */}
            {!isSelf && menuItem(
              user.is_active ? "Disable account" : "Enable account",
              () => patch({ is_active: !user.is_active }),
              !user.is_active ? false : true,
            )}

            {/* Role change */}
            {roles.map(r => menuItem(
              `Set role → ${r}`,
              () => patch({ role: r }),
              false,
            ))}

            {/* Divider */}
            {!isSelf && <div style={{ height: 1, background: "var(--rule-soft)", margin: "4px 0" }} />}

            {/* Delete */}
            {!isSelf && menuItem("Delete user", del, true)}
          </div>
        </>
      )}
    </div>
  );
}

// ─── Main view ────────────────────────────────────────────────────────────────
function UserManagement() {
  const [users, setUsers]       = useUsr([]);
  const [loading, setLoading]   = useUsr(true);
  const [showModal, setModal]   = useUsr(false);
  const [currentId, setCurrentId] = useUsr(null);

  const load = useUcb(async () => {
    setLoading(true);
    try {
      const res = await fetch("/api/users/");
      if (res.ok) {
        const data = await res.json();
        setUsers(data);
        // find own id
        const me = data.find(u => u.username === window.ArisAuth.getUsername());
        if (me) setCurrentId(me.id);
      }
    } catch (_) {}
    setLoading(false);
  }, []);

  useUef(() => { load(); }, [load]);

  const handleCreated = (u) => setUsers(prev => [...prev, u]);
  const handleUpdate  = (u) => setUsers(prev => prev.map(x => x.id === u.id ? u : x));
  const handleDelete  = (id) => setUsers(prev => prev.filter(x => x.id !== id));

  const th = { style: {
    fontFamily: "var(--font-mono)", fontSize: 9, letterSpacing: "0.14em",
    textTransform: "uppercase", color: "var(--fog)", textAlign: "left",
    padding: "0 12px 10px", fontWeight: 400, borderBottom: "1px solid var(--rule)",
  }};
  const td = { style: {
    padding: "12px 12px", borderBottom: "1px solid var(--rule-soft)",
    verticalAlign: "middle",
  }};

  return (
    <div>
      {/* ── Header ── */}
      <div style={{ marginBottom: 32, display: "flex", alignItems: "flex-end", justifyContent: "space-between" }}>
        <div>
          <div className="coord" style={{ marginBottom: 8 }}>§ 03 / SYS · USERS</div>
          <h1 style={{
            fontFamily: "var(--font-serif)", fontSize: 36, fontWeight: 400,
            letterSpacing: "-0.02em", margin: 0,
          }}>
            User Management
          </h1>
          <p style={{ marginTop: 8, color: "var(--ink-2)", fontSize: 14, maxWidth: "52ch" }}>
            Create and manage accounts. Roles control what each user can do across the CRM.
          </p>
        </div>
        <button onClick={() => setModal(true)} style={{
          padding: "9px 20px", background: "var(--accent)",
          border: "none", borderRadius: 1, cursor: "pointer",
          fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.12em",
          textTransform: "uppercase", color: "var(--paper)",
        }}>
          + New user
        </button>
      </div>

      {/* ── Role legend ── */}
      <div style={{
        display: "flex", gap: 24, marginBottom: 28,
        padding: "14px 18px", background: "var(--surface)",
        border: "1px solid var(--rule)", borderRadius: 1,
        fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--fog)",
      }}>
        {[
          { role: "admin",  desc: "Full CRUD + user management" },
          { role: "editor", desc: "Create & update records, no delete" },
          { role: "viewer", desc: "Read-only access" },
        ].map(({ role, desc }) => (
          <span key={role} style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <RoleBadge role={role} />
            <span style={{ color: "var(--fog)" }}>{desc}</span>
          </span>
        ))}
      </div>

      {/* ── Table ── */}
      <div style={{ background: "var(--surface)", border: "1px solid var(--rule)", borderRadius: 1 }}>
        {loading ? (
          <div style={{
            padding: 48, textAlign: "center",
            fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.16em",
            textTransform: "uppercase", color: "var(--fog)",
          }}>
            Loading…
          </div>
        ) : users.length === 0 ? (
          <div style={{
            padding: 48, textAlign: "center",
            fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.16em",
            textTransform: "uppercase", color: "var(--fog)",
          }}>
            No users found
          </div>
        ) : (
          <table style={{ width: "100%", borderCollapse: "collapse" }}>
            <thead>
              <tr>
                <th {...th}>Username</th>
                <th {...th}>Email</th>
                <th {...th}>Role</th>
                <th {...th}>Status</th>
                <th {...th}>Joined</th>
                <th {...th} style={{ ...th.style, textAlign: "right" }}>Actions</th>
              </tr>
            </thead>
            <tbody>
              {users.map(user => (
                <tr key={user.id} style={{ opacity: user.is_active ? 1 : 0.55 }}>
                  <td {...td}>
                    <span style={{
                      fontFamily: "var(--font-mono)", fontSize: 13, color: "var(--ink)",
                    }}>
                      {user.username}
                      {user.id === currentId && (
                        <span style={{
                          marginLeft: 8, fontFamily: "var(--font-mono)", fontSize: 8,
                          letterSpacing: "0.12em", textTransform: "uppercase",
                          color: "var(--fog)", border: "1px solid var(--rule-soft)",
                          borderRadius: 1, padding: "1px 5px",
                        }}>you</span>
                      )}
                    </span>
                  </td>
                  <td {...td}>
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--ink-2)" }}>
                      {user.email || "—"}
                    </span>
                  </td>
                  <td {...td}><RoleBadge role={user.role} /></td>
                  <td {...td}><StatusDot active={user.is_active} /></td>
                  <td {...td}>
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, color: "var(--fog)" }}>
                      {new Date(user.date_joined).toLocaleDateString("en-CA")}
                    </span>
                  </td>
                  <td {...td} style={{ ...td.style, textAlign: "right" }}>
                    <RowActions
                      user={user}
                      currentUserId={currentId}
                      onUpdate={handleUpdate}
                      onDelete={handleDelete}
                    />
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {/* ── New User Modal ── */}
      {showModal && (
        <NewUserModal
          onClose={() => setModal(false)}
          onCreated={handleCreated}
        />
      )}
    </div>
  );
}

Object.assign(window, { UserManagement });
