const Customers = ({ onOpenLead }) => {
  const t = useTheme();
  const isBloom = t.name === 'BLOOM';
  const [search, setSearch] = React.useState('');
  const { data: leads, loading } = useLeads();

  const leadsArray = Array.isArray(leads) ? leads : (leads?.data || []);
  const filtered = leadsArray.filter(l => 
    l.name.toLowerCase().includes(search.toLowerCase()) || 
    l.phone.includes(search)
  );

  return (
    <div style={{ padding: 32, maxWidth: 1000, margin: '0 auto' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 24 }}>
        <div>
          <h1 style={{ fontSize: 28, fontFamily: t.fontDisplay, margin: 0, color: t.text }}>Banco de Clientes</h1>
          <p style={{ margin: '4px 0 0', color: t.textMuted, fontSize: 14 }}>Visão geral de todos os contatos capturados</p>
        </div>
        <div style={{ position: 'relative' }}>
          <Icons.Search size={16} stroke={t.textMuted} style={{ position: 'absolute', left: 12, top: 12 }} />
          <input 
            type="text" 
            placeholder="Buscar por nome ou número..." 
            value={search}
            onChange={e => setSearch(e.target.value)}
            style={{
              padding: '10px 16px 10px 36px', width: 300,
              background: isBloom ? t.surface : 'rgba(255,255,255,0.03)',
              border: `1px solid ${t.border}`, borderRadius: t.radiusMd,
              color: t.text, fontFamily: t.fontBody, fontSize: 14, outline: 'none',
              boxShadow: isBloom ? '3px 3px 0 0 #14131A' : 'none',
            }}
          />
        </div>
      </div>

      <div style={{
        background: t.surface, borderRadius: t.radiusLg,
        border: `1px solid ${t.border}`, overflow: 'hidden',
        boxShadow: isBloom ? '6px 6px 0 0 #14131A' : '0 4px 20px rgba(0,0,0,0.2)',
      }}>
        {loading && <div style={{ padding: 40, textAlign: 'center', color: t.textMuted }}>Carregando clientes...</div>}
        {!loading && filtered.length === 0 && <div style={{ padding: 40, textAlign: 'center', color: t.textMuted }}>Nenhum cliente encontrado.</div>}
        
        {!loading && filtered.length > 0 && (
          <table style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left', fontSize: 13 }}>
            <thead>
              <tr style={{ borderBottom: `1px solid ${t.border}`, color: t.textMuted, fontFamily: t.fontMono, fontSize: 11 }}>
                <th style={{ padding: '16px 20px', fontWeight: 600 }}>NOME</th>
                <th style={{ padding: '16px 20px', fontWeight: 600 }}>TELEFONE</th>
                <th style={{ padding: '16px 20px', fontWeight: 600 }}>ETAPA ATUAL</th>
                <th style={{ padding: '16px 20px', fontWeight: 600 }}>IA ATIVA</th>
                <th style={{ padding: '16px 20px', fontWeight: 600, textAlign: 'right' }}>AÇÕES</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(lead => (
                <tr key={lead.id} style={{ borderBottom: `1px solid ${t.border}`, background: 'transparent' }}>
                  <td style={{ padding: '16px 20px', display: 'flex', alignItems: 'center', gap: 12 }}>
                    <div style={{ width: 32, height: 32, borderRadius: '50%', background: lead.color, display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', fontWeight: 700, fontSize: 12 }}>
                      {lead.name.substring(0,2).toUpperCase()}
                    </div>
                    <div style={{ fontWeight: 600, color: t.text }}>{lead.name}</div>
                  </td>
                  <td style={{ padding: '16px 20px', color: t.textMuted }}>{lead.phone}</td>
                  <td style={{ padding: '16px 20px' }}>
                    <span style={{ padding: '4px 8px', borderRadius: 99, background: t.surfaceAlt, color: t.text, fontSize: 11, fontWeight: 600, border: `1px solid ${t.border}` }}>
                      {lead.stage}
                    </span>
                  </td>
                  <td style={{ padding: '16px 20px' }}>
                    {lead.aiActive ? (
                      <span style={{ color: t.green, display: 'flex', alignItems: 'center', gap: 4, fontWeight: 600, fontSize: 11 }}><Icons.Check size={14}/> Ativa</span>
                    ) : (
                      <span style={{ color: t.textMuted, display: 'flex', alignItems: 'center', gap: 4, fontWeight: 600, fontSize: 11 }}><Icons.Power size={14}/> Pausada</span>
                    )}
                  </td>
                  <td style={{ padding: '16px 20px', textAlign: 'right' }}>
                    <Btn size="sm" onClick={() => onOpenLead(lead.id)}>Abrir CRM</Btn>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>
    </div>
  );
};

window.Customers = Customers;
