/* global React, IconLock, IconMail, IconUser, IconUsers, IconCheck, IconClose, IconPlus */
// Login screen + user management (admin only).

const { useState: _aus } = React;

function Avatar({ name, color, size = 34 }) {
  const initials = name.split(" ").map((s) => s[0]).slice(0, 2).join("").toUpperCase();
  return (
    <div className="rv-avatar" style={{ width: size, height: size, background: color || "var(--accent)", fontSize: size * 0.38 }}>
      {initials}
    </div>);
}

// ============ Login =============================================
function LoginScreen({ onLogin }) {
  const { USERS, CLOSERS } = window.REVOLVR_DATA;
  const [email, setEmail] = _aus("");
  const [password, setPassword] = _aus("");
  const [error, setError] = _aus("");

  const [loading, setLoading] = _aus(false);

  const submit = (e) => {
    e && e.preventDefault();
    setLoading(true);
    setError("");

    const tryLogin = (userList) => {
      const u = userList.find((x) => x.email.toLowerCase() === email.trim().toLowerCase());
      if (!u || u.password !== password) {
        setError("Correo o contraseña incorrectos.");
        setLoading(false);
        return;
      }
      if (!u.active) {
        setError("Tu usuario está desactivado. Contacta a un administrador.");
        setLoading(false);
        return;
      }
      setError("");
      setLoading(false);
      onLogin(u);
    };

    // Intentar desde Supabase primero, fallback a data.js
    if (window.SUPABASE) {
      window.SUPABASE.from("crm_users").select("*")
        .then(({ data, error }) => {
          if (!error && data && data.length > 0) {
            const mapped = data.map((u) => ({ id: u.id, name: u.name, email: u.email, password: u.password, role: u.role, closerId: u.closer_id, active: u.active, lastLogin: u.last_login || "" }));
            tryLogin(mapped);
          } else {
            tryLogin(USERS);
          }
        });
    } else {
      tryLogin(USERS);
    }
  };

  return (
    <div className="login-screen">
      <div className="login-card">
        <div className="login-brand">
          <img src="assets/revolvr-logo.png" alt="REVOLVR" className="login-logo"/>
          <div className="login-tag">CRM · Gestión de llamadas</div>
        </div>

        <form className="login-form" onSubmit={submit}>
          <label className="login-field">
            <span>Correo</span>
            <div className="login-input">
              <IconMail size={15}/>
              <input type="email" value={email} autoComplete="username"
                     onChange={(e) => setEmail(e.target.value)} placeholder="tu@revolvr.io"/>
            </div>
          </label>
          <label className="login-field">
            <span>Contraseña</span>
            <div className="login-input">
              <IconLock size={15}/>
              <input type="password" value={password} autoComplete="current-password"
                     onChange={(e) => setPassword(e.target.value)} placeholder="••••••••"/>
            </div>
          </label>
          {error && <div className="login-error">{error}</div>}
          <button className="crm-btn login-submit" data-variant="primary" type="submit" disabled={loading}>
            {loading ? "Verificando..." : "Iniciar sesión"}
          </button>
        </form>


      </div>
    </div>);
}

// ============ Administración de usuarios (admin) ================
function UsersView({ users, onAddUser, onToggleActive, onDeleteUser, onResetPassword, currentUser }) {
  const { CLOSERS } = window.REVOLVR_DATA;
  const [modal, setModal] = _aus(false);
  const [resetModal, setResetModal] = _aus(null); // usuario a resetear

  return (
    <div className="users-wrap">
      <div className="users-head">
        <div>
          <h2 className="users-title">Usuarios y accesos</h2>
          <div className="users-sub">{users.length} usuarios · {users.filter((u) => u.active).length} activos</div>
        </div>
        <button className="crm-btn" data-variant="primary" onClick={() => setModal(true)}>
          <IconPlus size={13}/> Nuevo usuario
        </button>
      </div>

      <table className="tbl">
        <thead>
          <tr>
            <th style={{ width: "30%" }}>Usuario</th>
            <th style={{ width: "26%" }}>Correo</th>
            <th style={{ width: "14%" }}>Rol</th>
            <th style={{ width: "16%" }}>Pipeline</th>
            <th style={{ width: "14%", textAlign: "right" }}>Estado</th>
            <th style={{ width: "8%", textAlign: "right" }}>Acciones</th>
          </tr>
        </thead>
        <tbody>
          {users.map((u) => {
            const c = CLOSERS.find((x) => x.id === u.closerId);
            return (
              <tr key={u.id}>
                <td>
                  <div className="name-cell">
                    <Avatar name={u.name} color={u.role === "admin" ? "#0d1419" : (c ? c.color : "var(--accent)")} size={28}/>
                    <div>
                      <div style={{ fontWeight: 600, fontSize: 13 }}>{u.name}</div>
                      <div style={{ fontSize: 11, color: "var(--text-3)" }}>Último acceso: {u.lastLogin}</div>
                    </div>
                  </div>
                </td>
                <td style={{ color: "var(--text-2)", fontFamily: "var(--font-mono)", fontSize: 11.5 }}>{u.email}</td>
                <td>
                  <span className="role-pill" data-role={u.role}>
                    {u.role === "admin" ? "Administrador" : "Closer"}
                  </span>
                </td>
                <td style={{ color: "var(--text-2)" }}>{c ? c.name : "— (todos)"}</td>
                <td style={{ textAlign: "right" }}>
                  <button className="toggle-pill" data-on={u.active ? "true" : undefined}
                          onClick={() => onToggleActive(u.id)}>
                    <span className="knob"/>
                    {u.active ? "Activo" : "Inactivo"}
                  </button>
                </td>
                <td style={{ textAlign: "right", display: "flex", gap: 4, justifyContent: "flex-end" }}>
                  <button className="crm-btn" data-variant="ghost"
                    style={{ fontSize: 11 }}
                    onClick={() => setResetModal(u)}>
                    Contraseña
                  </button>
                  {u.id !== currentUser?.id &&
                    <button className="crm-btn" data-variant="ghost"
                      style={{ color: "#ef4444", fontSize: 11 }}
                      onClick={() => { if (window.confirm("¿Eliminar a " + u.name + "?")) onDeleteUser(u.id); }}>
                      Eliminar
                    </button>}
                </td>
              </tr>);
          })}
        </tbody>
      </table>

      {modal && <NewUserModal onClose={() => setModal(false)} onSave={(u) => { onAddUser(u); setModal(false); }}/>}
      {resetModal && <ResetPasswordModal user={resetModal} onClose={() => setResetModal(null)} onSave={(id, pwd) => { onResetPassword(id, pwd); setResetModal(null); }}/>}
    </div>);
}

function NewUserModal({ onClose, onSave }) {
  const { CLOSERS } = window.REVOLVR_DATA;
  const [name, setName] = _aus("");
  const [email, setEmail] = _aus("");
  const [password, setPassword] = _aus("");
  const [role, setRole] = _aus("closer");
  const [closerId, setCloserId] = _aus("new");

  const field = {
    width: "100%", padding: "8px 10px", border: "1px solid var(--border)",
    borderRadius: "var(--radius-s)", background: "var(--surface)", color: "var(--text)",
    fontFamily: "inherit", fontSize: 12.5, marginTop: 4,
  };
  const lbl = { fontSize: 11, color: "var(--text-3)", fontWeight: 600, textTransform: "uppercase", letterSpacing: ".04em" };

  const save = () => {
    if (!name.trim() || !email.trim()) return;
    onSave({ name: name.trim(), email: email.trim(), password, role, closerId });
  };

  return (
    <div className="confirm-overlay" onClick={onClose}>
      <div className="confirm-modal" style={{ maxWidth: 440 }} onClick={(e) => e.stopPropagation()}>
        <h3>Nuevo usuario</h3>
        <p style={{ marginTop: -2 }}>Crea un acceso para un closer o administrador del equipo.</p>

        <div style={{ marginTop: 6 }}>
          <label style={lbl}>Nombre completo</label>
          <input value={name} onChange={(e) => setName(e.target.value)} style={field} placeholder="Ej. Carla Núñez"/>
        </div>
        <div style={{ marginTop: 10 }}>
          <label style={lbl}>Correo</label>
          <input value={email} onChange={(e) => setEmail(e.target.value)} style={field} placeholder="carla@revolvr.io"/>
        </div>
        <div style={{ marginTop: 10 }}>
          <label style={lbl}>Contraseña</label>
          <input value={password} onChange={(e) => setPassword(e.target.value)} style={field}/>
        </div>
        <div style={{ display: "flex", gap: 10, marginTop: 10 }}>
          <div style={{ flex: 1 }}>
            <label style={lbl}>Rol</label>
            <select value={role} onChange={(e) => setRole(e.target.value)} style={field}>
              <option value="closer">Closer</option>
              <option value="admin">Administrador</option>
            </select>
          </div>
          {role === "closer" &&
            <div style={{ flex: 1 }}>
              <label style={lbl}>Pipeline</label>
              <select value={closerId} onChange={(e) => setCloserId(e.target.value)} style={field}>
                <option value="new">Crear pipeline propio</option>
                {CLOSERS.map((c) => <option key={c.id} value={c.id}>{c.name}</option>)}
              </select>
            </div>}
        </div>

        <div className="actions">
          <button className="crm-btn" onClick={onClose}>Cancelar</button>
          <button className="crm-btn" data-variant="primary" onClick={save} disabled={!name.trim() || !email.trim()}>
            Crear usuario
          </button>
        </div>
      </div>
    </div>);
}

function ResetPasswordModal({ user, onClose, onSave }) {
  const [pwd, setPwd] = _aus("");
  const [confirm, setConfirm] = _aus("");
  const [err, setErr] = _aus("");

  const field = { width: "100%", padding: "8px 10px", border: "1px solid var(--border)", borderRadius: 7, fontFamily: "inherit", fontSize: 13, background: "var(--bg)", color: "var(--text-1)" };

  const save = () => {
    if (pwd.length < 6) { setErr("La contraseña debe tener al menos 6 caracteres."); return; }
    if (pwd !== confirm) { setErr("Las contraseñas no coinciden."); return; }
    onSave(user.id, pwd);
  };

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal-card" onClick={(e) => e.stopPropagation()}>
        <div className="modal-head">
          <h3>Resetear contraseña</h3>
        </div>
        <div style={{ fontSize: 13, color: "var(--text-2)", marginBottom: 16 }}>
          Cambiando contraseña de <strong>{user.name}</strong> ({user.email})
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
          <label style={{ fontSize: 12, fontWeight: 500, color: "var(--text-2)" }}>
            Nueva contraseña
            <input type="password" value={pwd} onChange={(e) => setPwd(e.target.value)}
              style={{ ...field, marginTop: 4 }} placeholder="Mínimo 6 caracteres"/>
          </label>
          <label style={{ fontSize: 12, fontWeight: 500, color: "var(--text-2)" }}>
            Confirmar contraseña
            <input type="password" value={confirm} onChange={(e) => setConfirm(e.target.value)}
              style={{ ...field, marginTop: 4 }} placeholder="Repite la contraseña"/>
          </label>
          {err && <div style={{ fontSize: 12, color: "#ef4444" }}>{err}</div>}
        </div>
        <div style={{ display: "flex", justifyContent: "flex-end", gap: 8, marginTop: 20 }}>
          <button className="crm-btn" data-variant="ghost" onClick={onClose}>Cancelar</button>
          <button className="crm-btn" data-variant="primary" onClick={save} disabled={!pwd || !confirm}>Guardar</button>
        </div>
      </div>
    </div>);
}

Object.assign(window, { LoginScreen, UsersView, Avatar });
