/* admin.jsx — Painel de administração de usuários (apenas role=admin). */

function AdminPanel({ onClose, pushToast, currentUserId }) {
  const { Ic } = window;
  const [list, setList] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [err, setErr] = React.useState("");
  const [showAdd, setShowAdd] = React.useState(false);

  // form de novo usuário
  const [form, setForm] = React.useState({
    name: "", email: "", password: "", role: "colaborador", role_title: "Membro"
  });
  const [creating, setCreating] = React.useState(false);

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

  const create = async (e) => {
    e.preventDefault();
    if (!form.name.trim() || !form.email.trim() || form.password.length < 12) {
      pushToast("⚠️", "Preencha nome, e-mail e senha (mín. 12)"); return;
    }
    setCreating(true);
    try {
      await window.Api.users.create(form);
      pushToast("✅", "Usuário criado");
      setForm({ name: "", email: "", password: "", role: "colaborador", role_title: "Membro" });
      setShowAdd(false);
      load();
    } catch (e) { pushToast("⚠️", e.message); }
    finally { setCreating(false); }
  };

  const setRole = async (u, role) => {
    try { await window.Api.users.update(u.id, { role }); load(); }
    catch (e) { pushToast("⚠️", e.message); }
  };
  const toggleActive = async (u) => {
    try { await window.Api.users.update(u.id, { is_active: !u.is_active }); load(); }
    catch (e) { pushToast("⚠️", e.message); }
  };
  const remove = async (u) => {
    if (!confirm(`Remover ${u.name} (${u.email})? Essa ação é irreversível.`)) return;
    try { await window.Api.users.remove(u.id); pushToast("🗑️", "Usuário removido"); load(); }
    catch (e) { pushToast("⚠️", e.message); }
  };
  const resetPw = async (u) => {
    const np = prompt(`Nova senha para ${u.name} (mín. 12 caracteres):`);
    if (np === null) return;
    if (np.length < 12) { pushToast("⚠️", "A senha precisa de no mínimo 12 caracteres"); return; }
    try { await window.Api.users.update(u.id, { password: np }); pushToast("🔒", "Senha redefinida"); }
    catch (e) { pushToast("⚠️", e.message); }
  };

  const roleMeta = {
    admin:       { cls: "role-admin" },
    gerente:     { cls: "role-gerente" },
    colaborador: { cls: "role-colab" },
  };
  const initials = (n) => (n || "U").trim().split(/\s+/).map(w => w[0]).slice(0, 2).join("").toUpperCase();

  const total  = list.length;
  const admins = list.filter(u => u.role === "admin").length;
  const ativos = list.filter(u => u.is_active).length;

  return (
    <div className="modal" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="modal-box admin-box">
        <button className="detail-close" style={{ top: 18, right: 18 }} onClick={onClose} aria-label="Fechar"><Ic.Close size={20} /></button>
        <h2>Administração</h2>
        <p className="sub">Gerencie usuários e permissões do painel.</p>

        <div className="admin-toolbar">
          <div className="admin-counts">
            <span className="admin-chip"><b>{total}</b> {total === 1 ? "usuário" : "usuários"}</span>
            <span className="admin-chip"><b>{ativos}</b> {ativos === 1 ? "ativo" : "ativos"}</span>
            <span className="admin-chip"><b>{admins}</b> admin{admins === 1 ? "" : "s"}</span>
          </div>
          <button className="btn-primary admin-add-btn" onClick={() => { setShowAdd(s => !s); setErr(""); }}>
            {showAdd ? <Ic.Close size={16} /> : <Ic.Plus size={16} />} {showAdd ? "Fechar" : "Novo usuário"}
          </button>
        </div>

        {showAdd && (
          <form onSubmit={create} className="admin-add">
            <div className="admin-add-grid">
              <div className="field"><label>Nome</label>
                <input className="input" value={form.name} onChange={e => setForm({ ...form, name: e.target.value })} required /></div>
              <div className="field"><label>E-mail</label>
                <input className="input" type="email" value={form.email} onChange={e => setForm({ ...form, email: e.target.value })} required /></div>
              <div className="field"><label>Senha inicial</label>
                <input className="input" type="text" value={form.password} onChange={e => setForm({ ...form, password: e.target.value })} placeholder="mín. 12 caracteres" required /></div>
              <div className="field"><label>Cargo (texto)</label>
                <input className="input" value={form.role_title} onChange={e => setForm({ ...form, role_title: e.target.value })} /></div>
              <div className="field"><label>Permissão</label>
                <select className="input" value={form.role} onChange={e => setForm({ ...form, role: e.target.value })}>
                  <option value="colaborador">Colaborador</option>
                  <option value="gerente">Gerente</option>
                  <option value="admin">Admin</option>
                </select></div>
            </div>
            <div className="admin-add-foot">
              <button type="button" className="btn-ghost" onClick={() => { setShowAdd(false); setErr(""); }}>Cancelar</button>
              <button type="submit" className="btn-primary" disabled={creating}>
                <Ic.Plus size={16} /> {creating ? "Criando…" : "Adicionar usuário"}
              </button>
            </div>
          </form>
        )}

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

        <div className="admin-list">
          {loading && <div className="admin-empty">Carregando…</div>}
          {!loading && list.length === 0 && <div className="admin-empty">Nenhum usuário cadastrado</div>}
          {!loading && list.map(u => {
            const isSelf = u.id === currentUserId;
            const rm = roleMeta[u.role] || roleMeta.colaborador;
            return (
              <div key={u.id} className={"admin-user" + (u.is_active ? "" : " off")}>
                <div className="admin-user-id">
                  {u.avatar
                    ? <img className="admin-avatar" src={u.avatar} alt="" />
                    : <span className="admin-avatar admin-avatar-init">{initials(u.name)}</span>}
                  <div className="admin-user-text">
                    <div className="admin-user-name">
                      <span className="ellip">{u.name}</span>
                      {isSelf && <span className="admin-you">você</span>}
                    </div>
                    <div className="admin-user-sub ellip">{u.role_title}</div>
                    <div className="admin-user-email ellip">{u.email}</div>
                  </div>
                </div>

                <div className="admin-user-ctl">
                  <select value={u.role} onChange={e => setRole(u, e.target.value)} className={"input admin-role " + rm.cls} title="Permissão">
                    <option value="colaborador">Colaborador</option>
                    <option value="gerente">Gerente</option>
                    <option value="admin">Admin</option>
                  </select>

                  <button
                    className={"admin-status" + (u.is_active ? " on" : "")}
                    onClick={() => toggleActive(u)}
                    disabled={isSelf}
                    title={isSelf ? "Você não pode desativar a si mesmo" : (u.is_active ? "Desativar" : "Ativar")}>
                    <span className="dot" /> {u.is_active ? "Ativo" : "Inativo"}
                  </button>

                  <div className="admin-user-acts">
                    <button className="icon-btn sm" onClick={() => resetPw(u)} title="Redefinir senha"><Ic.Lock size={16} /></button>
                    {!isSelf && (
                      <button className="icon-btn sm danger" onClick={() => remove(u)} title="Remover usuário"><Ic.Trash size={16} /></button>
                    )}
                  </div>
                </div>

                <div className="admin-user-meta">Último acesso: {u.last_login || "nunca"}</div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

window.AdminPanel = AdminPanel;
