// CronoDato — Admin screen

const AdminScreen = () => {
  const [clientes, setClientes] = React.useState([
    { id: '1', nombre: 'Estudio Contable López', emailRemitente: 'facturas@lopez.com.ar', emailReceptor: 'admin@lopez.com.ar', plan: 'mensual', topeMensual: 100, usadoMes: 23, saldo: 0, activo: true, retencion: 48, planilla: '1VNuOK...' },
    { id: '2', nombre: 'Distribuidora Norte',    emailRemitente: 'compras@dnorte.com',    emailReceptor: 'admin@dnorte.com',    plan: 'por_uso', topeMensual: 0,   usadoMes: 0,  saldo: 340, activo: true,  retencion: 72, planilla: '1ABC...' },
    { id: '3', nombre: 'Comercio El Sol',        emailRemitente: 'facturas@elsol.com.ar', emailReceptor: 'info@elsol.com.ar',   plan: 'por_uso', topeMensual: 0,   usadoMes: 0,  saldo: 0,   activo: false, retencion: 48, planilla: '' },
  ]);
  const [showModal, setShowModal] = React.useState(false);
  const [editando, setEditando] = React.useState(null);
  const [busqueda, setBusqueda] = React.useState('');

  const clienteVacio = { nombre: '', emailRemitente: '', emailReceptor: '', plan: 'por_uso', topeMensual: 100, usadoMes: 0, saldo: 0, activo: true, retencion: 48, planilla: '' };
  const [form, setForm] = React.useState(clienteVacio);

  const abrirNuevo = () => { setForm(clienteVacio); setEditando(null); setShowModal(true); };
  const abrirEditar = (c) => { setForm({ ...c }); setEditando(c.id); setShowModal(true); };
  const cerrarModal = () => { setShowModal(false); setEditando(null); };

  const guardar = () => {
    if (!form.nombre.trim()) return;
    if (editando) {
      setClientes(prev => prev.map(c => c.id === editando ? { ...form, id: editando } : c));
    } else {
      setClientes(prev => [...prev, { ...form, id: Date.now().toString() }]);
    }
    cerrarModal();
  };

  const toggleActivo = (id) => setClientes(prev => prev.map(c => c.id === id ? { ...c, activo: !c.activo } : c));

  const filtrados = clientes.filter(c =>
    c.nombre.toLowerCase().includes(busqueda.toLowerCase()) ||
    c.emailRemitente.toLowerCase().includes(busqueda.toLowerCase())
  );

  const Field = ({ label, value, onChange, type = 'text', placeholder, hint, mono }) => (
    <div>
      <label style={{ display: 'block', fontSize: 11, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: '#64748B', marginBottom: 5 }}>{label}</label>
      <input type={type} value={value} onChange={e => onChange(e.target.value)} placeholder={placeholder}
        style={{ width: '100%', fontFamily: mono ? "'DM Mono',monospace" : "'DM Sans',sans-serif", fontSize: 13, padding: '8px 10px', border: '1.5px solid #E2E8F0', borderRadius: 6, background: 'white', color: '#0F172A', outline: 'none' }}
        onFocus={e => { e.target.style.borderColor = '#059669'; e.target.style.boxShadow = '0 0 0 2px rgba(5,150,105,0.12)'; }}
        onBlur={e => { e.target.style.borderColor = '#E2E8F0'; e.target.style.boxShadow = 'none'; }}
      />
      {hint && <div style={{ fontSize: 11, color: '#94A3B8', marginTop: 3 }}>{hint}</div>}
    </div>
  );

  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      <Topbar
        title="Administración de clientes"
        subtitle={`${clientes.filter(c => c.activo).length} activos · ${clientes.length} total`}
        actions={
          <Btn onClick={abrirNuevo}>
            <i data-lucide="plus" style={{ width: 15, height: 15 }}></i> Nuevo cliente
          </Btn>
        }
      />

      <div style={{ flex: 1, overflowY: 'auto', padding: 24 }}>
        {/* Stats rápidas */}
        <div style={{ display: 'flex', gap: 12, marginBottom: 24 }}>
          <StatCard label="Clientes activos"  value={clientes.filter(c => c.activo).length}  color="#059669" />
          <StatCard label="Plan mensual"      value={clientes.filter(c => c.plan === 'mensual').length}  color="#1D4ED8" />
          <StatCard label="Plan por uso"      value={clientes.filter(c => c.plan === 'por_uso').length} color="#D97706" />
          <StatCard label="Sin saldo"         value={clientes.filter(c => c.plan === 'por_uso' && c.saldo === 0).length} color="#DC2626" />
        </div>

        {/* Búsqueda */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'white', border: '1px solid #E2E8F0', borderRadius: 7, padding: '8px 14px', marginBottom: 16, maxWidth: 320 }}>
          <i data-lucide="search" style={{ width: 15, height: 15, color: '#94A3B8' }}></i>
          <input
            value={busqueda} onChange={e => setBusqueda(e.target.value)}
            placeholder="Buscar cliente…"
            style={{ border: 'none', background: 'transparent', fontSize: 13, color: '#0F172A', outline: 'none', width: '100%', fontFamily: "'DM Sans',sans-serif" }}
          />
        </div>

        {/* Tabla */}
        <div style={{ background: 'white', border: '1px solid #E2E8F0', borderRadius: 10, overflow: 'hidden' }}>
          <div style={{ overflowX: 'auto' }}>
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 13 }}>
              <thead>
                <tr style={{ background: '#F8FAFC' }}>
                  {['Cliente', 'Email remitente', 'Plan', 'Uso / Saldo', 'Retención', 'Estado', ''].map(h => (
                    <th key={h} style={{ padding: '10px 16px', textAlign: 'left', fontSize: 11, fontWeight: 600, letterSpacing: '0.05em', textTransform: 'uppercase', color: '#94A3B8', borderBottom: '1px solid #E2E8F0', whiteSpace: 'nowrap' }}>{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody>
                {filtrados.map((c, i) => (
                  <tr key={c.id} style={{ borderBottom: i < filtrados.length - 1 ? '1px solid #F1F5F9' : 'none' }}
                    onMouseEnter={e => e.currentTarget.style.background = '#F8FAFC'}
                    onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                    <td style={{ padding: '12px 16px' }}>
                      <div style={{ fontWeight: 600, color: '#0F172A' }}>{c.nombre}</div>
                      <div style={{ fontSize: 11, color: '#94A3B8' }}>{c.emailReceptor}</div>
                    </td>
                    <td style={{ padding: '12px 16px', fontFamily: "'DM Mono',monospace", fontSize: 12, color: '#64748B' }}>{c.emailRemitente}</td>
                    <td style={{ padding: '12px 16px' }}>
                      <span style={{
                        fontSize: 11, fontWeight: 500, padding: '2px 8px', borderRadius: 9999,
                        background: c.plan === 'mensual' ? '#ECFDF5' : '#EFF6FF',
                        color: c.plan === 'mensual' ? '#047857' : '#1D4ED8',
                      }}>
                        {c.plan === 'mensual' ? 'Mensual' : 'Por uso'}
                      </span>
                    </td>
                    <td style={{ padding: '12px 16px', fontFamily: "'DM Mono',monospace", fontSize: 12, color: '#0F172A' }}>
                      {c.plan === 'mensual'
                        ? <span>{c.usadoMes} / {c.topeMensual}</span>
                        : <span style={{ color: c.saldo === 0 ? '#DC2626' : '#047857' }}>Saldo: {c.saldo}</span>
                      }
                    </td>
                    <td style={{ padding: '12px 16px', fontSize: 12, color: '#64748B' }}>{c.retencion}hs</td>
                    <td style={{ padding: '12px 16px' }}>
                      <div
                        onClick={() => toggleActivo(c.id)}
                        style={{
                          width: 38, height: 22, borderRadius: 11, background: c.activo ? '#059669' : '#E2E8F0',
                          position: 'relative', cursor: 'pointer', transition: 'background 150ms',
                        }}
                      >
                        <div style={{
                          width: 16, height: 16, borderRadius: '50%', background: 'white',
                          position: 'absolute', top: 3, left: c.activo ? 19 : 3,
                          transition: 'left 150ms', boxShadow: '0 1px 3px rgba(0,0,0,0.15)',
                        }} />
                      </div>
                    </td>
                    <td style={{ padding: '12px 16px' }}>
                      <button
                        onClick={() => abrirEditar(c)}
                        style={{ fontFamily: "'DM Sans',sans-serif", fontSize: 12, fontWeight: 500, padding: '5px 12px', background: 'white', color: '#475569', border: '1px solid #E2E8F0', borderRadius: 5, cursor: 'pointer' }}
                        onMouseEnter={e => e.currentTarget.style.background = '#F1F5F9'}
                        onMouseLeave={e => e.currentTarget.style.background = 'white'}
                      >
                        Editar
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>

      {/* Modal */}
      {showModal && (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 100, padding: 20 }}
          onClick={e => { if (e.target === e.currentTarget) cerrarModal(); }}>
          <div style={{ background: 'white', borderRadius: 12, width: '100%', maxWidth: 560, maxHeight: '85vh', overflow: 'hidden', display: 'flex', flexDirection: 'column', boxShadow: '0 24px 48px rgba(0,0,0,0.2)' }}>
            <div style={{ padding: '18px 24px', borderBottom: '1px solid #E2E8F0', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexShrink: 0 }}>
              <div style={{ fontSize: 16, fontWeight: 700, color: '#0F172A' }}>{editando ? 'Editar cliente' : 'Nuevo cliente'}</div>
              <button onClick={cerrarModal} style={{ background: 'none', border: 'none', cursor: 'pointer', color: '#94A3B8', display: 'flex', padding: 4, borderRadius: 4 }}
                onMouseEnter={e => { e.currentTarget.style.background = '#F1F5F9'; e.currentTarget.style.color = '#475569'; }}
                onMouseLeave={e => { e.currentTarget.style.background = 'none'; e.currentTarget.style.color = '#94A3B8'; }}>
                <i data-lucide="x" style={{ width: 18, height: 18 }}></i>
              </button>
            </div>

            <div style={{ flex: 1, overflowY: 'auto', padding: 24 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                <div style={{ gridColumn: '1/-1' }}>
                  <Field label="Nombre / Razón social" value={form.nombre} onChange={v => setForm(p => ({ ...p, nombre: v }))} placeholder="Estudio Contable López" />
                </div>
                <Field label="Email remitente" value={form.emailRemitente} onChange={v => setForm(p => ({ ...p, emailRemitente: v }))} placeholder="facturas@empresa.com" hint="Desde donde envía facturas" />
                <Field label="Email receptor" value={form.emailReceptor} onChange={v => setForm(p => ({ ...p, emailReceptor: v }))} placeholder="admin@empresa.com" hint="Email de contacto" />
                <div style={{ gridColumn: '1/-1' }}>
                  <Field label="ID Planilla Google Sheets" value={form.planilla} onChange={v => setForm(p => ({ ...p, planilla: v }))} placeholder="1VNuOK9Ee-J9xHv..." mono hint="ID del Google Sheet del cliente" />
                </div>

                <div>
                  <label style={{ display: 'block', fontSize: 11, fontWeight: 600, letterSpacing: '0.06em', textTransform: 'uppercase', color: '#64748B', marginBottom: 5 }}>Plan</label>
                  <select value={form.plan} onChange={e => setForm(p => ({ ...p, plan: e.target.value }))}
                    style={{ width: '100%', fontFamily: "'DM Sans',sans-serif", fontSize: 13, padding: '8px 10px', border: '1.5px solid #E2E8F0', borderRadius: 6, background: 'white', color: '#0F172A', outline: 'none', cursor: 'pointer' }}>
                    <option value="mensual">Mensual</option>
                    <option value="por_uso">Por uso</option>
                  </select>
                </div>

                {form.plan === 'mensual' ? (
                  <>
                    <Field label="Tope mensual" type="number" value={form.topeMensual} onChange={v => setForm(p => ({ ...p, topeMensual: parseInt(v) || 0 }))} placeholder="100" />
                    <Field label="Usado este mes" type="number" value={form.usadoMes} onChange={v => setForm(p => ({ ...p, usadoMes: parseInt(v) || 0 }))} placeholder="0" />
                  </>
                ) : (
                  <Field label="Saldo de facturas" type="number" value={form.saldo} onChange={v => setForm(p => ({ ...p, saldo: parseInt(v) || 0 }))} placeholder="200" hint="Cantidad de facturas disponibles" />
                )}

                <Field label="Retención Dropbox (hs)" type="number" value={form.retencion} onChange={v => setForm(p => ({ ...p, retencion: parseInt(v) || 48 }))} placeholder="48" />

                <div style={{ display: 'flex', alignItems: 'center', gap: 10, paddingTop: 20 }}>
                  <div
                    onClick={() => setForm(p => ({ ...p, activo: !p.activo }))}
                    style={{ width: 40, height: 22, borderRadius: 11, background: form.activo ? '#059669' : '#E2E8F0', position: 'relative', cursor: 'pointer', transition: 'background 150ms' }}
                  >
                    <div style={{ width: 16, height: 16, borderRadius: '50%', background: 'white', position: 'absolute', top: 3, left: form.activo ? 21 : 3, transition: 'left 150ms', boxShadow: '0 1px 3px rgba(0,0,0,0.15)' }} />
                  </div>
                  <span style={{ fontSize: 14, fontWeight: 500, color: '#475569' }}>Cliente activo</span>
                </div>
              </div>
            </div>

            <div style={{ padding: '16px 24px', borderTop: '1px solid #E2E8F0', display: 'flex', gap: 10, justifyContent: 'flex-end', flexShrink: 0 }}>
              <Btn variant="ghost" onClick={cerrarModal}>Cancelar</Btn>
              <Btn onClick={guardar}>{editando ? 'Guardar cambios' : 'Crear cliente'}</Btn>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

Object.assign(window, { AdminScreen });
