/* === Panel admin de cuentas (solo admin) ===
   La protección REAL está en el backend (requireAdmin). Esta vista degrada limpio
   si listAccounts responde no-autorizado. */

const UsuariosView = ({ user, role }) => {
  const [rows, setRows] = React.useState(null); // null = cargando
  const [error, setError] = React.useState("");
  const [editId, setEditId] = React.useState(null);
  const [email, setEmail] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const [msg, setMsg] = React.useState("");

  const load = async () => {
    setError("");
    try {
      const list = await window.cdcAuth.listAccounts();
      setRows(list || []);
    } catch (e) {
      setRows([]);
      setError("No tienes permiso para administrar cuentas, o hubo un error de conexión.");
    }
  };
  React.useEffect(() => { load(); }, []);

  if (role !== "admin") {
    return <div style={{ padding: 28, color: "var(--cdc-ink-3)" }}>No tienes acceso a esta sección.</div>;
  }

  const startEdit = (r) => { setEditId(r.staffId); setEmail(r.email || ""); setPassword(""); setMsg(""); };
  const cancel = () => { setEditId(null); setEmail(""); setPassword(""); setMsg(""); };

  const save = async (staffId) => {
    if (busy) return;
    setMsg("");
    if (!email.includes("@")) { setMsg("Correo no válido."); return; }
    if (password.length < 8) { setMsg("La contraseña debe tener al menos 8 caracteres."); return; }
    setBusy(true);
    try {
      await window.cdcAuth.upsertAccount(staffId, email.trim().toLowerCase(), password);
      await load();
      cancel();
    } catch (e) {
      setMsg("No se pudo guardar: " + ((e && e.message) || "error"));
    } finally { setBusy(false); }
  };

  const remove = async (staffId, name) => {
    if (busy) return;
    if (!window.confirm("¿Quitar la cuenta de " + name + "?")) return;
    setBusy(true); setMsg("");
    try { await window.cdcAuth.removeAccount(staffId); await load(); }
    catch (e) { setMsg("No se pudo quitar: " + ((e && e.message) || "error")); }
    finally { setBusy(false); }
  };

  const roleLabel = { admin: "Controller", gerente: "Manager", jefe: "Jefe de área", staff: "Staff", compras: "Compras" };

  return (
    <div style={{ padding: 28, maxWidth: 760 }}>
      <h2 style={{ fontFamily: "var(--cdc-display)", fontSize: 26, fontWeight: 600, color: "var(--cdc-ink)", margin: "0 0 4px" }}>
        Cuentas de personal
      </h2>
      <p style={{ fontSize: 13.5, color: "var(--cdc-ink-3)", margin: "0 0 20px" }}>
        Asigna correo y contraseña a cada persona. Solo tú (admin) ves esta sección.
      </p>

      {error && (
        <div style={{ background: "var(--cdc-urgent-bg)", color: "var(--cdc-urgent)", padding: "10px 14px", borderRadius: 10, marginBottom: 16, fontSize: 13.5 }}>
          {error}
        </div>
      )}
      {msg && (
        <div style={{ background: "var(--cdc-pending-bg)", color: "var(--cdc-pending)", padding: "10px 14px", borderRadius: 10, marginBottom: 16, fontSize: 13.5 }}>
          {msg}
        </div>
      )}
      {rows === null && <div style={{ color: "var(--cdc-ink-3)" }}>Cargando…</div>}

      <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
        {(rows || []).map((r) => {
          const s = (window.STAFF_BY_ID && window.STAFF_BY_ID[r.staffId]) || {};
          const name = s.name || r.staffId;
          const isSelf = r.staffId === user.id;
          const editing = editId === r.staffId;
          return (
            <div key={r.staffId} style={{ border: "1px solid var(--cdc-border)", borderRadius: 12, background: "var(--cdc-panel)", padding: 14 }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12 }}>
                <div>
                  <div style={{ fontWeight: 700, color: "var(--cdc-ink)" }}>
                    {name} {isSelf && <span style={{ color: "var(--cdc-ink-4)", fontWeight: 500 }}>(tú)</span>}
                  </div>
                  <div style={{ fontSize: 12.5, color: "var(--cdc-ink-3)" }}>
                    {(s.title || "")}{s.title ? " · " : ""}{roleLabel[r.role] || r.role}
                  </div>
                  <div style={{ fontSize: 12.5, marginTop: 3, color: r.hasAccount ? "var(--cdc-done)" : "var(--cdc-ink-4)" }}>
                    {r.hasAccount ? ("Cuenta: " + r.email) : "Sin cuenta"}
                  </div>
                </div>
                {!editing && (
                  <div style={{ display: "flex", gap: 8, flexShrink: 0 }}>
                    <button className="cdc-btn" onClick={() => startEdit(r)}>
                      {r.hasAccount ? "Restablecer" : "Crear cuenta"}
                    </button>
                    {r.hasAccount && !isSelf && (
                      <button className="cdc-btn" style={{ color: "var(--cdc-urgent)" }} onClick={() => remove(r.staffId, name)}>
                        Quitar
                      </button>
                    )}
                  </div>
                )}
              </div>

              {editing && (
                <div style={{ marginTop: 12, display: "flex", flexWrap: "wrap", gap: 10, alignItems: "flex-end" }}>
                  <div style={{ flex: "1 1 220px" }}>
                    <label style={{ display: "block", fontSize: 12, fontWeight: 600, color: "var(--cdc-ink-2)", marginBottom: 5 }}>Correo</label>
                    <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} disabled={busy}
                      style={{ width: "100%", boxSizing: "border-box", padding: "9px 11px", border: "1px solid var(--cdc-border)", borderRadius: 9, background: "var(--cdc-bg-soft)" }} />
                  </div>
                  <div style={{ flex: "1 1 200px" }}>
                    <label style={{ display: "block", fontSize: 12, fontWeight: 600, color: "var(--cdc-ink-2)", marginBottom: 5 }}>Contraseña (mín. 8)</label>
                    <input type="text" value={password} onChange={(e) => setPassword(e.target.value)} disabled={busy} placeholder="Nueva contraseña"
                      style={{ width: "100%", boxSizing: "border-box", padding: "9px 11px", border: "1px solid var(--cdc-border)", borderRadius: 9, background: "var(--cdc-bg-soft)" }} />
                  </div>
                  <div style={{ display: "flex", gap: 8 }}>
                    <button className="cdc-btn" onClick={cancel} disabled={busy}>Cancelar</button>
                    <button className="cdc-btn" onClick={() => save(r.staffId)} disabled={busy}
                      style={{ background: "var(--cdc-coral)", color: "#fff", borderColor: "var(--cdc-coral)" }}>
                      {busy ? "Guardando…" : "Guardar"}
                    </button>
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
};

Object.assign(window, { UsuariosView });
