/* global React, PR */
const { useState, useEffect, useCallback } = React;
const { I, Avatar } = PR;

const ROLE_LABELS = {
  admin:  "Admin",
  lead:   "R&D Lead",
  core:   "Designer",
  orbit:  "Analyst",
  viewer: "Viewer",
};

const ROLE_DESCS = {
  admin:  "Full access including user management and system settings.",
  lead:   "Full access. Approves pitch sessions and stage gates.",
  core:   "Authors hypotheses. Edits own projects, comments on others.",
  orbit:  "Owns telemetry and Cold Test data. Attaches reports.",
  viewer: "Read-only. Procurement uses this to receive scaled packages.",
};

const ROLE_PERMS = {
  admin:  ["Edit registry", "Move stages", "Kill / Pivot / Scale", "Manage users", "System settings"],
  lead:   ["Edit registry", "Move stages", "Decide Kill / Pivot / Scale", "Manage users"],
  core:   ["Create hypothesis", "Edit own", "Comment", "Move own to next stage"],
  orbit:  ["Edit metrics", "Attach reports", "Comment"],
  viewer: ["Read", "Export passport"],
};

function fmtLast(s) {
  if (!s) return "—";
  const d = new Date(s);
  if (isNaN(d.getTime())) return "—";
  const diff = Math.floor((Date.now() - d.getTime()) / 86400000);
  if (diff <= 0) return "today";
  if (diff === 1) return "1d ago";
  if (diff < 30) return diff + "d ago";
  return Math.floor(diff / 30) + "mo ago";
}

function InviteModal({ onClose, onSuccess }) {
  const [form, setForm] = useState({ username: "", email: "", full_name: "", role: "core", password: "" });
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState("");
  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));

  const handleSubmit = async (e) => {
    e.preventDefault();
    setSaving(true);
    setError("");
    try {
      const resp = await fetch("/api/users", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(form),
      });
      if (!resp.ok) {
        const err = await resp.json();
        setError(err.detail || "Failed to create user");
        return;
      }
      onSuccess();
      onClose();
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()} style={{ maxWidth: 440 }}>
        <div className="modal-head">
          <div className="modal-title">Invite member</div>
          <button className="modal-close" onClick={onClose}>×</button>
        </div>
        <form onSubmit={handleSubmit}>
          <div className="modal-body">
            {error && <div style={{ color: "var(--kill)", fontSize: 12, marginBottom: 12 }}>{error}</div>}
            <div className="form-row">
              <label className="form-label">Full name</label>
              <input className="form-input" value={form.full_name} onChange={e => set("full_name", e.target.value)} placeholder="Jane Doe" />
            </div>
            <div className="form-row">
              <label className="form-label">Username *</label>
              <input className="form-input" required value={form.username} onChange={e => set("username", e.target.value)} placeholder="jdoe" />
            </div>
            <div className="form-row">
              <label className="form-label">Email *</label>
              <input className="form-input" required type="email" value={form.email} onChange={e => set("email", e.target.value)} placeholder="jane@studio.dev" />
            </div>
            <div className="form-row">
              <label className="form-label">Password *</label>
              <input className="form-input" required type="password" value={form.password} onChange={e => set("password", e.target.value)} placeholder="••••••••" />
            </div>
            <div className="form-row">
              <label className="form-label">Role</label>
              <select className="form-select" value={form.role} onChange={e => set("role", e.target.value)}>
                <option value="admin">Admin</option>
                <option value="lead">R&D Lead</option>
                <option value="core">Designer (Core)</option>
                <option value="orbit">Analyst (Orbit)</option>
                <option value="viewer">Viewer</option>
              </select>
            </div>
          </div>
          <div className="modal-foot">
            <button type="button" className="btn btn-ghost" onClick={onClose}>Cancel</button>
            <button type="submit" className="btn btn-primary" disabled={saving}>{saving ? "Creating…" : "Create member"}</button>
          </div>
        </form>
      </div>
    </div>
  );
}

function UsersView({ data }) {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState("all");
  const [showInvite, setShowInvite] = useState(false);

  const load = useCallback(async () => {
    const resp = await fetch("/api/users");
    if (resp.ok) setUsers(await resp.json());
    setLoading(false);
  }, []);

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

  const toggleActive = async (u) => {
    await fetch(`/api/users/${u.id}`, {
      method: "PUT",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ is_active: !u.is_active }),
    });
    load();
  };

  if (loading) return <div style={{ padding: 40, color: "var(--text-3)" }}>Loading…</div>;

  const active = users.filter(u => u.is_active).length;
  const deactivated = users.filter(u => !u.is_active).length;
  const byRole = {};
  users.forEach(u => { const r = u.role || "core"; byRole[r] = (byRole[r] || 0) + 1; });
  const allRoles = Object.keys(ROLE_LABELS);

  const rows = filter === "all" ? users :
    filter === "active" ? users.filter(u => u.is_active) :
    filter === "deactivated" ? users.filter(u => !u.is_active) :
    users.filter(u => u.role === filter);

  return (
    <div className="users-wrap">
      <div className="users-stats">
        <div className="kpi-card">
          <div className="label">Members</div>
          <div className="value">{users.length}</div>
          <div className="delta">{active} active · {deactivated} deactivated</div>
        </div>
        <div className="kpi-card">
          <div className="label">Seats used</div>
          <div className="value">{active}<span style={{ fontSize: 16, color: "var(--text-3)" }}> / 20</span></div>
          <div className="delta">Pilot plan</div>
        </div>
        <div className="kpi-card">
          <div className="label">Roles defined</div>
          <div className="value">{allRoles.length}</div>
          <div className="delta">Admin can edit</div>
        </div>
        <div className="kpi-card">
          <div className="label">Teams</div>
          <div className="value">{[...new Set(users.map(u => u.role).filter(Boolean))].length}</div>
          <div className="delta">Active roles in use</div>
        </div>
      </div>

      <div style={{ padding: "0 24px 8px" }}>
        <div className="section-title" style={{ marginBottom: 8 }}>Roles &amp; permissions</div>
      </div>
      <div className="role-grid">
        {allRoles.map(r => (
          <div key={r} className="role-card">
            <div className="role-head">
              <span className="role-name">{ROLE_LABELS[r]}</span>
              <span className="role-count">{byRole[r] || 0}</span>
            </div>
            <p className="role-desc">{ROLE_DESCS[r]}</p>
            <div className="role-perms">
              {(ROLE_PERMS[r] || []).map(p => (
                <div key={p} className="role-perm">
                  <span className="check">{I.check}</span>
                  <span>{p}</span>
                </div>
              ))}
            </div>
          </div>
        ))}
      </div>

      <div style={{ padding: "0 24px 6px" }}>
        <div className="section-title" style={{ marginBottom: 8 }}>Members</div>
      </div>
      <div className="users-toolbar">
        <span className={"chip" + (filter === "all" ? " active" : "")} onClick={() => setFilter("all")}>All {users.length}</span>
        <span className={"chip" + (filter === "active" ? " active" : "")} onClick={() => setFilter("active")}>Active {active}</span>
        <span className={"chip" + (filter === "deactivated" ? " active" : "")} onClick={() => setFilter("deactivated")}>Deactivated {deactivated}</span>
        <span className="chip-divider"></span>
        {allRoles.map(r => (
          <span key={r} className={"chip" + (filter === r ? " active" : "")} onClick={() => setFilter(r)}>
            {ROLE_LABELS[r]} {byRole[r] || 0}
          </span>
        ))}
        <div style={{ marginLeft: "auto", display: "flex", gap: 6 }}>
          <button className="btn btn-primary" onClick={() => setShowInvite(true)}>{I.plus}<span>Invite member</span></button>
        </div>
      </div>

      <table className="table">
        <thead>
          <tr>
            <th>Name</th>
            <th style={{ width: 130 }}>Role</th>
            <th style={{ width: 140 }}>Username</th>
            <th style={{ width: 120 }}>Status</th>
            <th style={{ width: 130 }}>Actions</th>
          </tr>
        </thead>
        <tbody>
          {rows.map(u => {
            const author = { name: u.full_name || u.username, color: u.color || "#7C8BA1" };
            return (
              <tr key={u.id}>
                <td>
                  <div className="user-name-row">
                    <Avatar author={author} />
                    <div>
                      <div className="nm">{u.full_name || u.username}</div>
                      <div className="em">{u.email}</div>
                    </div>
                  </div>
                </td>
                <td><span className="role-tag">{ROLE_LABELS[u.role] || u.role}</span></td>
                <td><span className="cell-date" style={{ color: "var(--text-2)" }}>{u.username}</span></td>
                <td>
                  <span className="user-row-status" data-s={u.is_active ? "active" : "deactivated"}>
                    <span className="dot"></span>
                    {u.is_active ? "Active" : "Deactivated"}
                  </span>
                </td>
                <td>
                  <div style={{ display: "flex", gap: 4 }}>
                    {u.is_active ? (
                      <button className="btn btn-ghost" style={{ height: 24, padding: "0 8px", fontSize: 11.5, color: "var(--kill)" }} onClick={() => toggleActive(u)}>Deactivate</button>
                    ) : (
                      <button className="btn btn-ghost" style={{ height: 24, padding: "0 8px", fontSize: 11.5 }} onClick={() => toggleActive(u)}>Reactivate</button>
                    )}
                  </div>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>

      {showInvite && <InviteModal onClose={() => setShowInvite(false)} onSuccess={load} />}
    </div>
  );
}

window.PRUsers = { UsersView };
