// admin-users.jsx — Gestión de usuarios (solo admin) y bandeja de leads
const { useState, useEffect, useMemo } = React;

// ════════════════════════════════════════════════════════════════════
//   USUARIOS
// ════════════════════════════════════════════════════════════════════
const UsersScreen = ({ profile, onTab, onLogout }) => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [showForm, setShowForm] = useState(false);
  const [form, setForm] = useState({ email: '', password: '', nombre: '', role: 'vendedor' });
  const [submitting, setSubmitting] = useState(false);

  const load = async () => {
    setLoading(true);
    try {
      const list = await window.OMEGA_STORE.listUsers();
      setUsers(list || []);
    } catch (e) {
      window.__adm_toast({ msg: 'Error al cargar usuarios: ' + e.message, type: 'error' });
    } finally { setLoading(false); }
  };

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

  const submit = async (e) => {
    e.preventDefault();
    setSubmitting(true);
    try {
      await window.OMEGA_STORE.createUser(form.email, form.password, form.role, form.nombre);
      window.__adm_toast({ msg: 'Usuario creado · revisá tu email si Supabase pide confirmación', type:'success' });
      setShowForm(false);
      setForm({ email: '', password: '', nombre: '', role: 'vendedor' });
      await load();
    } catch (e) {
      window.__adm_toast({ msg: e.message || 'No pude crear el usuario', type: 'error' });
    } finally { setSubmitting(false); }
  };

  const changeRole = async (userId, newRole) => {
    try {
      await window.OMEGA_STORE.updateUserRole(userId, newRole);
      window.__adm_toast({ msg: 'Rol actualizado', type:'success' });
      await load();
    } catch (e) {
      window.__adm_toast({ msg: 'No pude cambiar el rol: ' + e.message, type: 'error' });
    }
  };

  return (
    <React.Fragment>
      <AdminTopBar profile={profile} active="usuarios" onTab={onTab} onLogout={onLogout}/>
      <main className="adm-main">
        <div className="adm-pagehead">
          <div>
            <div className="eyebrow">Equipo OMEGA</div>
            <h1>Usuarios del panel</h1>
          </div>
          <div className="adm-pagehead-actions">
            <button className="btn btn-accent btn-lg" onClick={()=>setShowForm(true)}>
              <AIcon.Plus width="14" height="14"/> Nuevo usuario
            </button>
          </div>
        </div>

        {loading ? (
          <div style={{padding:60, textAlign:'center', color:'var(--ink-dim)', fontFamily:'var(--mono)', fontSize:11, letterSpacing:'0.16em'}}>CARGANDO USUARIOS...</div>
        ) : (
          <table className="adm-table">
            <thead>
              <tr>
                <th>Nombre / Email</th>
                <th>Rol</th>
                <th>Creado</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {users.map(u => (
                <tr key={u.id} className="adm-row">
                  <td>
                    <div className="adm-cell-title">{u.nombre || '—'}</div>
                    <div className="adm-cell-sub">{u.email}</div>
                  </td>
                  <td>
                    <span className={`adm-status ${u.role === 'admin' ? 'published' : 'draft'}`} style={{cursor:'default'}}>
                      {u.role}
                    </span>
                  </td>
                  <td className="adm-cell-mono">{new Date(u.created_at).toLocaleDateString('es-AR')}</td>
                  <td style={{textAlign:'right'}}>
                    {u.id !== profile.id && (
                      <select
                        className="adm-filter-select"
                        style={{minWidth:120}}
                        value={u.role}
                        onChange={(e)=>changeRole(u.id, e.target.value)}
                      >
                        <option value="vendedor">vendedor</option>
                        <option value="admin">admin</option>
                      </select>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </main>

      {showForm && (
        <div className="adm-modal-overlay" onClick={()=>setShowForm(false)}>
          <div className="adm-modal" onClick={e=>e.stopPropagation()} style={{maxWidth:520}}>
            <h3>Nuevo usuario</h3>
            <form onSubmit={submit} style={{textAlign:'left'}}>
              <div className="editor-grid" style={{marginBottom:16}}>
                <div className="editor-field-wide">
                  <label className="adm-input-label">Nombre completo</label>
                  <input className="adm-input" required value={form.nombre} onChange={(e)=>setForm({...form, nombre: e.target.value})}/>
                </div>
                <div className="editor-field-wide">
                  <label className="adm-input-label">Email</label>
                  <input className="adm-input" type="email" required value={form.email} onChange={(e)=>setForm({...form, email: e.target.value})}/>
                </div>
                <div className="editor-field-wide">
                  <label className="adm-input-label">Contraseña inicial</label>
                  <input className="adm-input" type="text" required minLength="8" value={form.password} onChange={(e)=>setForm({...form, password: e.target.value})}/>
                  <div className="adm-input-help">Mínimo 8 caracteres · el usuario podrá cambiarla después</div>
                </div>
                <div className="editor-field-wide">
                  <label className="adm-input-label">Rol</label>
                  <div className="adm-tag-picker">
                    {['vendedor', 'admin'].map(r => (
                      <button type="button" key={r}
                        className={`adm-tag-opt ${form.role === r ? 'on' : ''}`}
                        onClick={()=>setForm({...form, role: r})}
                      >{r}</button>
                    ))}
                  </div>
                </div>
              </div>
              <div className="adm-modal-actions">
                <button type="button" className="btn btn-ghost" onClick={()=>setShowForm(false)} disabled={submitting}>Cancelar</button>
                <button type="submit" className="btn btn-accent" disabled={submitting}>
                  {submitting ? 'Creando...' : 'Crear usuario'}
                </button>
              </div>
            </form>
          </div>
        </div>
      )}
    </React.Fragment>
  );
};

// ════════════════════════════════════════════════════════════════════
//   LEADS / CONSULTAS
// ════════════════════════════════════════════════════════════════════
const LeadsScreen = ({ profile, onTab, onLogout, vehicles }) => {
  const [leads, setLeads] = useState([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState('todos'); // todos / pendientes / contactados / busquedas

  const load = async () => {
    setLoading(true);
    try {
      const list = await window.OMEGA_STORE.listLeads();
      setLeads(list || []);
    } catch (e) {
      window.__adm_toast({ msg: 'Error al cargar leads: ' + e.message, type: 'error' });
    } finally { setLoading(false); }
  };

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

  const filtered = useMemo(() => {
    return leads.filter(l => {
      if (filter === 'pendientes' && l.contactado) return false;
      if (filter === 'contactados' && !l.contactado) return false;
      if (filter === 'busquedas' && l.tipo !== 'busqueda') return false;
      if (filter === 'consultas' && l.tipo === 'busqueda') return false;
      return true;
    });
  }, [leads, filter]);

  const stats = useMemo(() => ({
    total: leads.length,
    pendientes: leads.filter(l => !l.contactado).length,
    busquedas: leads.filter(l => l.tipo === 'busqueda').length
  }), [leads]);

  const toggleContactado = async (id, contactado) => {
    try {
      await window.OMEGA_STORE.updateLead(id, { contactado: !contactado });
      await load();
    } catch (e) {
      window.__adm_toast({ msg: 'Error: ' + e.message, type:'error' });
    }
  };

  const fmtDate = (s) => {
    const d = new Date(s);
    return d.toLocaleDateString('es-AR') + ' ' + d.toLocaleTimeString('es-AR', { hour: '2-digit', minute: '2-digit' });
  };

  const vehicleOf = (id) => vehicles?.find(v => v.id === id);

  return (
    <React.Fragment>
      <AdminTopBar profile={profile} active="leads" onTab={onTab} onLogout={onLogout}/>
      <main className="adm-main">
        <div className="adm-pagehead">
          <div>
            <div className="eyebrow">Bandeja de entrada</div>
            <h1>Consultas y pedidos</h1>
          </div>
        </div>

        <div className="adm-stats">
          <div className="adm-stat">
            <div className="adm-stat-label">Total recibidos</div>
            <div className="adm-stat-value">{stats.total}</div>
          </div>
          <div className="adm-stat">
            <div className="adm-stat-label">Pendientes</div>
            <div className="adm-stat-value accent">{stats.pendientes}</div>
          </div>
          <div className="adm-stat">
            <div className="adm-stat-label">Búsquedas (red de agencias)</div>
            <div className="adm-stat-value">{stats.busquedas}</div>
          </div>
          <div className="adm-stat">
            <div className="adm-stat-label">Tasa de respuesta</div>
            <div className="adm-stat-value" style={{fontSize:28, marginTop:14}}>
              {stats.total ? Math.round((stats.total - stats.pendientes) / stats.total * 100) : 0}%
            </div>
          </div>
        </div>

        <div className="adm-toolbar">
          <select className="adm-filter-select" value={filter} onChange={(e)=>setFilter(e.target.value)}>
            <option value="todos">Todos los leads</option>
            <option value="pendientes">Sólo pendientes</option>
            <option value="contactados">Ya contactados</option>
            <option value="busquedas">Búsquedas a la red</option>
            <option value="consultas">Consultas de catálogo</option>
          </select>
        </div>

        {loading ? (
          <div style={{padding:60, textAlign:'center', color:'var(--ink-dim)', fontFamily:'var(--mono)', fontSize:11, letterSpacing:'0.16em'}}>CARGANDO LEADS...</div>
        ) : filtered.length === 0 ? (
          <div className="adm-empty">
            <div className="eyebrow">Sin consultas</div>
            <h3>Bandeja vacía</h3>
            <p style={{color:'var(--ink-dim)'}}>Cuando el sitio reciba consultas, aparecen acá.</p>
          </div>
        ) : (
          <div className="leads-list">
            {filtered.map(l => {
              const v = vehicleOf(l.vehicle_id);
              return (
                <div key={l.id} className={`lead-card ${l.contactado ? 'done' : ''}`}>
                  <div className="lead-card-head">
                    <div>
                      <span className={`adm-status ${l.contactado ? 'published' : 'draft'}`}>
                        {l.tipo === 'busqueda' ? '🔍 Búsqueda' : l.tipo === 'contacto' ? '📩 Contacto' : '🚗 Vehículo'}
                      </span>
                      <span className="lead-date mono">{fmtDate(l.created_at)}</span>
                    </div>
                    <button
                      className="btn btn-sm"
                      style={l.contactado ? {} : {background:'var(--accent)', color:'white', borderColor:'var(--accent)'}}
                      onClick={()=>toggleContactado(l.id, l.contactado)}
                    >
                      {l.contactado ? <><AIcon.Check width="13" height="13"/> Contactado</> : 'Marcar como contactado'}
                    </button>
                  </div>
                  <div className="lead-card-body">
                    <div className="lead-contact">
                      <div className="lead-name">{l.nombre || 'Sin nombre'}</div>
                      <div className="lead-info mono">
                        {l.telefono && <span>📞 {l.telefono}</span>}
                        {l.email && <span>✉ {l.email}</span>}
                      </div>
                    </div>
                    <div className="lead-detail">
                      {v && (
                        <div className="lead-vehicle">
                          <strong>Vehículo:</strong> {v.marca} {v.modelo} ({v.anio}) — {fmtPriceARS(v.precio)}
                        </div>
                      )}
                      {l.tipo === 'busqueda' && (
                        <div className="lead-search">
                          <strong>Busca:</strong>{' '}
                          {[l.marca_buscada, l.modelo_buscado, l.carroceria_buscada, l.anio_desde && `desde ${l.anio_desde}`, l.presupuesto && `hasta ${fmtPriceARS(l.presupuesto)}`]
                            .filter(Boolean).join(' · ')}
                        </div>
                      )}
                      {l.mensaje && <div className="lead-msg">"{l.mensaje}"</div>}
                    </div>
                  </div>
                  {l.telefono && (
                    <div className="lead-card-actions">
                      <a className="btn btn-sm" target="_blank" href={`https://wa.me/${l.telefono.replace(/\D/g,'')}`}>
                        WhatsApp
                      </a>
                      {l.email && <a className="btn btn-sm" href={`mailto:${l.email}`}>Email</a>}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        )}
      </main>
    </React.Fragment>
  );
};

Object.assign(window, { UsersScreen, LeadsScreen });
