/* approvals.jsx — Fila de aprovação de cadastros (admin + gerente). */

const APPROVAL_ROLES = [
  { v: "colaborador", label: "Colaborador", base: true },
  { v: "gerente", label: "Gerente", base: false },
  { v: "admin", label: "Admin", base: false },
];
const initialsOf = (name) =>
  (name || "?").trim().split(/\s+/).map(w => w[0]).slice(0, 2).join("").toUpperCase();

function ApprovalsPanel({ onClose, onChanged, pushToast, currentRole }) {
  const { Ic } = window;
  const [list, setList] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [busyId, setBusyId] = React.useState(null);
  const [err, setErr] = React.useState("");
  // role escolhido por usuário (default colaborador)
  const [roles, setRoles] = React.useState({});

  const load = async () => {
    setLoading(true); setErr("");
    try {
      const r = await window.Api.approvals.list();
      setList(r.pending || []);
      onChanged && onChanged(r.count);
    } catch (e) { setErr(e.message); }
    finally { setLoading(false); }
  };
  React.useEffect(() => { load(); }, []);

  const approve = async (u) => {
    setBusyId(u.id);
    try {
      const role = roles[u.id] || "colaborador";
      await window.Api.approvals.approve(u.id, { role });
      pushToast("✅", `${u.name} aprovado como ${role}`);
      load();
    } catch (e) { pushToast("⚠️", e.message); }
    finally { setBusyId(null); }
  };

  const reject = async (u) => {
    if (!confirm(`Rejeitar a solicitação de ${u.name} (${u.email})?`)) return;
    setBusyId(u.id);
    try {
      await window.Api.approvals.reject(u.id);
      pushToast("🗑️", "Solicitação rejeitada");
      load();
    } catch (e) { pushToast("⚠️", e.message); }
    finally { setBusyId(null); }
  };

  const setRole = (uid, v) => setRoles(r => ({ ...r, [uid]: v }));

  const fmtDate = (s) => {
    if (!s) return "—";
    try {
      const d = new Date(s.replace(" ", "T"));
      return d.toLocaleString("pt-BR", { dateStyle: "short", timeStyle: "short" });
    } catch (_) { return s; }
  };

  return (
    <div className="modal" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal-box settings-box" style={{ width: 620, maxWidth: "100%" }}>
        <button className="detail-close" style={{ top: 18, right: 18 }} onClick={onClose} aria-label="Fechar">
          <Ic.Close size={20} />
        </button>
        <h2>Solicitações de cadastro</h2>
        <p className="sub">
          Aprove ou rejeite quem solicitou acesso pelo formulário público.
          {currentRole === "gerente" && " Gerentes só podem aprovar como colaborador."}
        </p>

        {err && <p className="form-err">{err}</p>}

        <div className="approvals-list">
          {loading && <div style={{ padding: 20, textAlign: "center", color: "var(--txt-3)" }}>Carregando…</div>}

          {!loading && list.length === 0 && (
            <div style={{ padding: 32, textAlign: "center", color: "var(--txt-3)" }}>
              <div style={{ fontSize: 36, marginBottom: 8 }}>🎉</div>
              Nenhuma solicitação pendente.
            </div>
          )}

          {!loading && list.map(u => {
            const role = roles[u.id] || "colaborador";
            const isAdmin = currentRole === "admin";
            const blockedRole = !isAdmin && role !== "colaborador";
            const busy = busyId === u.id;
            return (
              <div key={u.id} className="approval-card">
                <div className="approval-head">
                  <span className="approval-avatar">{initialsOf(u.name)}</span>
                  <div className="approval-info">
                    <b>{u.name}</b>
                    <span className="approval-email">{u.email}</span>
                    <span className="approval-time">
                      <Ic.Clock size={12} /> solicitado em {fmtDate(u.created_at)}
                    </span>
                  </div>
                </div>
                <div className="approval-actions">
                  <div className="role-seg" role="group" aria-label="Definir cargo">
                    {APPROVAL_ROLES.map(r => {
                      const locked = !r.base && !isAdmin;
                      return (
                        <button key={r.v} type="button" data-role={r.v}
                          className={"role-seg-btn" + (role === r.v ? " on" : "")}
                          disabled={locked || busy}
                          onClick={() => setRole(u.id, r.v)}
                          title={locked ? "Somente admin pode atribuir este cargo" : "Aprovar como " + r.label}>
                          {locked && <Ic.Lock size={12} />}{r.label}
                        </button>
                      );
                    })}
                  </div>
                  <div className="approval-btns">
                    <button className="btn-ghost danger" onClick={() => reject(u)} disabled={busy}>
                      <Ic.Trash size={16} /> Rejeitar
                    </button>
                    <button className="btn-primary" onClick={() => approve(u)} disabled={busy || blockedRole}>
                      <Ic.Check size={16} /> {busy ? "Aprovando…" : "Aprovar"}
                    </button>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

window.ApprovalsPanel = ApprovalsPanel;
