'use client';

import { useEffect, useState, FormEvent, useRef } from 'react';
import * as XLSX from 'xlsx';
import Header from '@/components/header';
import Modal from '@/components/modal';
import api from '@/lib/api';
import { useCep } from '@/hooks/use-cep';
import { Client } from '@/types';

// ── Types ──────────────────────────────────────────────────────
type ClientRow = {
  type: string; document: string; name: string;
  address: string; addressNumber: string; neighborhood: string;
  uf: string; zipCode: string;
  phoneCommercial: string; phoneFinancial: string;
  emailCommercial: string; emailFinancial: string; emailNf: string;
};

type LookupStatus = 'fetching' | 'found' | 'not_found' | 'error';
type ImportStatus = 'pending' | 'importing' | 'done' | 'error';

type LookupRow = {
  cnpj: string;
  lookupStatus: LookupStatus;
  data?: ClientRow;
  importStatus: ImportStatus;
  importError?: string;
};

// ── XLSX — extract CNPJs only ──────────────────────────────────
function parseXlsxCnpjs(buffer: ArrayBuffer): string[] {
  const wb = XLSX.read(buffer, { type: 'array' });
  const ws = wb.Sheets[wb.SheetNames[0]];
  const rows: Record<string, string>[] = XLSX.utils.sheet_to_json(ws, { defval: '' });
  if (rows.length === 0) return [];

  const headers = Object.keys(rows[0]);
  const cnpjCol = headers.find((h) =>
    ['cnpj', 'cpf', 'documento', 'document'].includes(h.trim().toLowerCase()),
  );

  const seen = new Set<string>();
  const cnpjs: string[] = [];

  for (const row of rows) {
    const rawVal = cnpjCol
      ? String(row[cnpjCol] ?? '')
      : Object.values(row).map(String).find((v) => v.replace(/\D/g, '').length === 14) ?? '';

    const clean = rawVal.replace(/\D/g, '');
    if (clean.length === 14 && !seen.has(clean)) {
      seen.add(clean);
      cnpjs.push(clean);
    }
  }
  return cnpjs;
}

// ── Template download — only CNPJ column ──────────────────────
function downloadTemplate() {
  const ws = XLSX.utils.aoa_to_sheet([
    ['CNPJ'],
    ['00000000000100'],
    ['11222333000181'],
  ]);
  ws['!cols'] = [{ wch: 22 }];
  ws['!autofilter'] = { ref: 'A1' };
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, 'Clientes');
  XLSX.writeFile(wb, 'modelo_importacao_clientes.xlsx');
}

// ── BrasilAPI lookup ───────────────────────────────────────────
async function fetchCnpj(cnpj: string): Promise<ClientRow | null> {
  try {
    const res = await fetch(`https://brasilapi.com.br/api/cnpj/v1/${cnpj}`);
    if (!res.ok) return null;
    const d = await res.json();
    return {
      type: 'PJ',
      document: cnpj,
      name: d.razao_social ?? '',
      address: d.logradouro ?? '',
      addressNumber: d.numero ?? '',
      neighborhood: d.bairro ?? '',
      uf: d.uf ?? '',
      zipCode: (d.cep ?? '').replace(/\D/g, ''),
      phoneCommercial: (d.ddd_telefone_1 ?? '').replace(/\D/g, ''),
      phoneFinancial: '',
      emailCommercial: d.email?.toLowerCase() ?? '',
      emailFinancial: '',
      emailNf: '',
    };
  } catch {
    return null;
  }
}

// ── XLSX preview modal ─────────────────────────────────────────
function XlsxPreviewModal({
  cnpjs, onClose, onDone,
}: {
  cnpjs: string[];
  onClose: () => void;
  onDone: () => void;
}) {
  const [rows, setRows] = useState<LookupRow[]>(
    cnpjs.map((cnpj) => ({ cnpj, lookupStatus: 'fetching', importStatus: 'pending' })),
  );
  const [phase, setPhase] = useState<'lookup' | 'import'>('lookup');

  // Fetch all CNPJs on mount
  useEffect(() => {
    let cancelled = false;
    (async () => {
      for (let i = 0; i < cnpjs.length; i++) {
        if (cancelled) break;
        const data = await fetchCnpj(cnpjs[i]);
        setRows((prev) =>
          prev.map((r, j) =>
            j === i
              ? { ...r, lookupStatus: data ? 'found' : 'not_found', data: data ?? undefined }
              : r,
          ),
        );
      }
    })();
    return () => { cancelled = true; };
  }, []);  // eslint-disable-line react-hooks/exhaustive-deps

  const lookupDone   = rows.every((r) => r.lookupStatus !== 'fetching');
  const foundRows    = rows.filter((r) => r.lookupStatus === 'found');
  const notFoundRows = rows.filter((r) => r.lookupStatus === 'not_found');
  const importDone   = foundRows.every((r) => r.importStatus === 'done' || r.importStatus === 'error');
  const importedOk   = rows.filter((r) => r.importStatus === 'done').length;
  const importedErr  = rows.filter((r) => r.importStatus === 'error').length;

  async function runImport() {
    setPhase('import');
    for (let i = 0; i < rows.length; i++) {
      if (rows[i].lookupStatus !== 'found' || !rows[i].data) continue;
      setRows((prev) => prev.map((r, j) => j === i ? { ...r, importStatus: 'importing' } : r));
      try {
        const payload = Object.fromEntries(
          Object.entries(rows[i].data!).filter(([, v]) => String(v).trim() !== ''),
        );
        await api.post('/clients', payload);
        setRows((prev) => prev.map((r, j) => j === i ? { ...r, importStatus: 'done' } : r));
      } catch (err: any) {
        const msg = err.response?.data?.message ?? 'Erro';
        setRows((prev) => prev.map((r, j) => j === i ? { ...r, importStatus: 'error', importError: msg } : r));
      }
    }
  }

  const total = cnpjs.length;

  return (
    <Modal open onClose={onClose} title={`Importar clientes — ${total} CNPJ${total !== 1 ? 's' : ''}`} wide>
      <div className="space-y-4">

        {/* Lookup phase */}
        {!lookupDone && (
          <p className="text-sm text-[#B7895A]">
            Consultando Receita Federal... ({rows.filter((r) => r.lookupStatus !== 'fetching').length}/{total})
          </p>
        )}

        {lookupDone && phase === 'lookup' && (
          <p className="text-sm text-[#0E0F12]/50">
            <strong className="text-green-600">{foundRows.length} encontrado{foundRows.length !== 1 ? 's' : ''}</strong>
            {notFoundRows.length > 0 && (
              <>, <strong className="text-red-500">{notFoundRows.length} não encontrado{notFoundRows.length !== 1 ? 's' : ''}</strong></>
            )}.
            {foundRows.length > 0 && ' Revise os dados antes de importar.'}
          </p>
        )}

        {phase === 'import' && importDone && (
          <p className="text-sm text-[#0E0F12]/60">
            Concluído: <strong className="text-green-600">{importedOk} importado{importedOk !== 1 ? 's' : ''}</strong>
            {importedErr > 0 && <>, <strong className="text-red-600">{importedErr} erro{importedErr !== 1 ? 's' : ''}</strong></>}.
          </p>
        )}

        {/* Table */}
        <div className="overflow-x-auto max-h-72 border border-[#EAE4D9] rounded-lg">
          <table className="w-full text-xs">
            <thead className="bg-[#FAF7F2] sticky top-0">
              <tr>
                <th className="px-3 py-2 text-left font-medium text-[#0E0F12]/60">CNPJ</th>
                <th className="px-3 py-2 text-left font-medium text-[#0E0F12]/60">Razão Social</th>
                <th className="px-3 py-2 text-left font-medium text-[#0E0F12]/60">Email</th>
                <th className="px-3 py-2 text-left font-medium text-[#0E0F12]/60">Telefone</th>
                <th className="px-3 py-2 text-left font-medium text-[#0E0F12]/60">UF</th>
                <th className="px-3 py-2 text-left font-medium text-[#0E0F12]/60">Status</th>
              </tr>
            </thead>
            <tbody className="divide-y divide-[#EAE4D9]">
              {rows.map((r, i) => (
                <tr
                  key={i}
                  className={
                    r.importStatus === 'done' ? 'bg-green-50'
                    : r.importStatus === 'error' ? 'bg-red-50'
                    : r.lookupStatus === 'not_found' ? 'bg-[#FAF7F2] opacity-60'
                    : ''
                  }
                >
                  <td className="px-3 py-2 font-mono text-[#0E0F12]/60">{r.cnpj}</td>
                  <td className="px-3 py-2 text-[#0E0F12] font-medium">{r.data?.name ?? '—'}</td>
                  <td className="px-3 py-2 text-[#0E0F12]/50">{r.data?.emailCommercial || '—'}</td>
                  <td className="px-3 py-2 text-[#0E0F12]/50">{r.data?.phoneCommercial || '—'}</td>
                  <td className="px-3 py-2 text-[#0E0F12]/50">{r.data?.uf || '—'}</td>
                  <td className="px-3 py-2 whitespace-nowrap">
                    {r.lookupStatus === 'fetching'  && <span className="text-[#B7895A]">buscando...</span>}
                    {r.lookupStatus === 'not_found' && <span className="text-[#0E0F12]/40">Não encontrado</span>}
                    {r.lookupStatus === 'found' && r.importStatus === 'pending'   && <span className="text-[#0E0F12]/40">Aguardando</span>}
                    {r.lookupStatus === 'found' && r.importStatus === 'importing' && <span className="text-[#B7895A]">importando...</span>}
                    {r.importStatus === 'done'  && <span className="text-green-600 font-medium">OK</span>}
                    {r.importStatus === 'error' && <span className="text-red-600" title={r.importError}>Erro</span>}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="flex justify-end gap-3 pt-1">
          <button
            className="btn-secondary"
            onClick={() => { onClose(); if (importDone && importedOk > 0) onDone(); }}
          >
            {importDone ? 'Fechar' : 'Cancelar'}
          </button>

          {lookupDone && phase === 'lookup' && foundRows.length > 0 && (
            <button className="btn-primary" onClick={runImport}>
              Importar {foundRows.length} cliente{foundRows.length !== 1 ? 's' : ''}
            </button>
          )}

          {importDone && importedOk > 0 && (
            <button className="btn-primary" onClick={() => { onClose(); onDone(); }}>
              Concluir
            </button>
          )}
        </div>
      </div>
    </Modal>
  );
}

// ── EMPTY form ─────────────────────────────────────────────────
const EMPTY_FORM = {
  type: 'PJ', document: '', name: '', email: '', phone: '',
  address: '', addressNumber: '', neighborhood: '', uf: '', zipCode: '', ibgeCode: '',
  phoneCommercial: '', phoneFinancial: '',
  emailCommercial: '', emailFinancial: '', emailNf: '',
  status: 'active',
};

async function lookupCnpj(cnpj: string) {
  const clean = cnpj.replace(/\D/g, '');
  if (clean.length !== 14) return null;
  const res = await fetch(`https://brasilapi.com.br/api/cnpj/v1/${clean}`);
  if (!res.ok) return null;
  return res.json();
}

// ── Types para contratos ───────────────────────────────────────
type ContractItem = { id: string; name: string; quantity: number; unitPrice: number; total: number };
type Contract = {
  id: string; number: string; title?: string; status: string;
  startDate: string; endDate?: string; total: number; items: ContractItem[];
};

const CONTRACT_STATUS: Record<string, { label: string; color: string }> = {
  draft:              { label: 'Rascunho',   color: '#B7895A' },
  pending_signature:  { label: 'Aguard. ass.', color: '#F59E0B' },
  active:             { label: 'Ativo',      color: '#16A34A' },
  cancelled:          { label: 'Cancelado',  color: '#EF4444' },
  terminated:         { label: 'Distrato',   color: '#6B7280' },
  finished:           { label: 'Encerrado',  color: '#6B7280' },
};

function formatDate(d: string) {
  try { return new Date(d + 'T00:00:00').toLocaleDateString('pt-BR'); } catch { return d; }
}

function brl(val: number) {
  return new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(val);
}

// ── Modal de contratos do cliente ─────────────────────────────
function ContratosModal({ client, onClose }: { client: Client; onClose: () => void }) {
  const [contracts, setContracts] = useState<Contract[] | null>(null);
  const [loading, setLoading]     = useState(true);
  const [expanded, setExpanded]   = useState<string | null>(null);

  useEffect(() => {
    api.get(`/contracts?clientId=${client.id}`)
      .then((r) => setContracts(r.data))
      .catch(() => setContracts([]))
      .finally(() => setLoading(false));
  }, [client.id]);

  return (
    <Modal open onClose={onClose} title={`Compras — ${client.name}`} wide>
      {loading ? (
        <p className="text-sm text-[#0E0F12]/50">Carregando...</p>
      ) : !contracts || contracts.length === 0 ? (
        <p className="text-sm text-[#0E0F12]/50">Nenhum contrato encontrado para este cliente.</p>
      ) : (
        <div className="space-y-2">
          <p className="text-xs text-[#0E0F12]/40 mb-3">
            {contracts.length} {contracts.length === 1 ? 'contrato' : 'contratos'}
          </p>
          {contracts.map((c) => {
            const st = CONTRACT_STATUS[c.status] ?? { label: c.status, color: '#6B7280' };
            const open = expanded === c.id;
            return (
              <div key={c.id} className="border border-[#EAE4D9] rounded-lg overflow-hidden">
                <button
                  className="w-full flex items-center gap-3 px-4 py-3 text-left hover:bg-[#FAF7F2] transition-colors"
                  onClick={() => setExpanded(open ? null : c.id)}
                >
                  <span className="font-mono text-xs text-[#0E0F12]/40 w-24 shrink-0">#{c.number}</span>
                  <span className="flex-1 text-sm font-medium text-[#0E0F12] truncate">
                    {c.title || 'Contrato'}
                  </span>
                  <span className="text-xs font-medium" style={{ color: st.color }}>{st.label}</span>
                  <span className="text-sm font-semibold text-[#0E0F12] ml-2 shrink-0">{brl(Number(c.total))}</span>
                  <span className="text-[#0E0F12]/30 text-xs ml-1">{open ? '▲' : '▼'}</span>
                </button>

                {open && (
                  <div className="border-t border-[#EAE4D9] bg-[#FAF7F2] px-4 py-3 space-y-3">
                    <div className="flex gap-6 text-xs text-[#0E0F12]/50">
                      <span>Início: {formatDate(c.startDate)}</span>
                      {c.endDate && <span>Fim: {formatDate(c.endDate)}</span>}
                    </div>
                    {c.items && c.items.length > 0 && (
                      <table className="w-full text-xs">
                        <thead>
                          <tr className="text-[#0E0F12]/40">
                            <th className="text-left py-1 font-medium">Item</th>
                            <th className="text-right py-1 font-medium w-16">Qtd</th>
                            <th className="text-right py-1 font-medium w-24">Unit.</th>
                            <th className="text-right py-1 font-medium w-24">Total</th>
                          </tr>
                        </thead>
                        <tbody className="divide-y divide-[#EAE4D9]">
                          {c.items.map((it) => (
                            <tr key={it.id}>
                              <td className="py-1.5 text-[#0E0F12]">{it.name}</td>
                              <td className="py-1.5 text-right text-[#0E0F12]/60">{Number(it.quantity)}</td>
                              <td className="py-1.5 text-right text-[#0E0F12]/60">{brl(Number(it.unitPrice))}</td>
                              <td className="py-1.5 text-right font-medium text-[#0E0F12]">{brl(Number(it.total))}</td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    )}
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}
    </Modal>
  );
}

// ── Main page ──────────────────────────────────────────────────
export default function ClientesPage() {
  const [items, setItems]     = useState<Client[]>([]);
  const [loading, setLoading] = useState(true);
  const [open, setOpen]       = useState(false);
  const [editId, setEditId]   = useState<string | null>(null);
  const [form, setForm]       = useState(EMPTY_FORM);
  const [saving, setSaving]             = useState(false);
  const [error, setError]               = useState('');
  const [inactivating, setInactivating] = useState<string | null>(null);
  const [cnpjLoading, setCnpjLoading] = useState(false);
  const cnpjTimer   = useRef<ReturnType<typeof setTimeout> | null>(null);
  const xlsxInputRef = useRef<HTMLInputElement>(null);
  const [xlsxCnpjs, setXlsxCnpjs] = useState<string[] | null>(null);
  const [clienteCompras, setClienteCompras] = useState<Client | null>(null);

  const { loading: cepLoading, handleChange: handleCepChange } = useCep((addr) => {
    setForm((prev) => ({
      ...prev,
      address:      addr.street || prev.address,
      neighborhood: addr.neighborhood || prev.neighborhood,
      uf:           addr.uf || prev.uf,
    }));
  });

  function load() {
    setLoading(true);
    api.get('/clients').then((r) => setItems(r.data.data ?? r.data)).catch(() => {}).finally(() => setLoading(false));
  }

  useEffect(load, []);

  function set(field: string, value: string) {
    setForm((prev) => ({ ...prev, [field]: value }));
    if (field === 'document' && form.type === 'PJ') {
      if (cnpjTimer.current) clearTimeout(cnpjTimer.current);
      const clean = value.replace(/\D/g, '');
      if (clean.length === 14) {
        cnpjTimer.current = setTimeout(async () => {
          setCnpjLoading(true);
          try {
            const data = await lookupCnpj(clean);
            if (data) {
              setForm((prev) => ({
                ...prev,
                name:            data.razao_social ?? prev.name,
                emailCommercial: data.email?.toLowerCase() ?? prev.emailCommercial,
                phoneCommercial: data.ddd_telefone_1 ? data.ddd_telefone_1.replace(/\D/g, '') : prev.phoneCommercial,
                zipCode:         data.cep?.replace(/\D/g, '') ?? prev.zipCode,
                address:         data.logradouro ?? prev.address,
                addressNumber:   data.numero ?? prev.addressNumber,
                neighborhood:    data.bairro ?? prev.neighborhood,
                uf:              data.uf ?? prev.uf,
                ibgeCode:        data.codigo_municipio_ibge ? String(data.codigo_municipio_ibge) : prev.ibgeCode,
              }));
            }
          } catch {}
          finally { setCnpjLoading(false); }
        }, 600);
      }
    }
  }

  function openModal() {
    setEditId(null);
    setForm(EMPTY_FORM);
    setError('');
    setOpen(true);
  }

  function openEdit(c: Client) {
    setEditId(c.id);
    setForm({
      type:            c.type ?? 'PJ',
      document:        c.document ?? '',
      name:            c.name ?? '',
      email:           (c as any).email ?? '',
      phone:           (c as any).phone ?? '',
      address:         (c as any).address ?? '',
      addressNumber:   (c as any).addressNumber ?? '',
      neighborhood:    (c as any).neighborhood ?? '',
      uf:              (c as any).uf ?? '',
      zipCode:         (c as any).zipCode ?? '',
      ibgeCode:        (c as any).ibgeCode ?? '',
      phoneCommercial: (c as any).phoneCommercial ?? '',
      phoneFinancial:  (c as any).phoneFinancial ?? '',
      emailCommercial: (c as any).emailCommercial ?? '',
      emailFinancial:  (c as any).emailFinancial ?? '',
      emailNf:         (c as any).emailNf ?? '',
      status:          c.status ?? 'active',
    });
    setError('');
    setOpen(true);
  }

  async function handleInactivate(id: string, name: string) {
    if (!confirm(`Inativar o cliente "${name}"? Ele não aparecerá mais na lista.`)) return;
    setInactivating(id);
    try {
      await api.delete(`/clients/${id}`);
      load();
    } catch (err: any) {
      alert(err.response?.data?.message ?? 'Erro ao inativar cliente');
    } finally {
      setInactivating(null);
    }
  }

  function handleXlsxFile(e: React.ChangeEvent<HTMLInputElement>) {
    const file = e.target.files?.[0];
    if (!file) return;
    e.target.value = '';
    const reader = new FileReader();
    reader.onload = (ev) => {
      try {
        const cnpjs = parseXlsxCnpjs(ev.target?.result as ArrayBuffer);
        if (cnpjs.length === 0) {
          alert('Nenhum CNPJ encontrado. O arquivo deve ter uma coluna "CNPJ" com os CNPJs a importar.');
          return;
        }
        setXlsxCnpjs(cnpjs);
      } catch {
        alert('Erro ao ler o arquivo XLSX.');
      }
    };
    reader.readAsArrayBuffer(file);
  }

  async function handleSubmit(e: FormEvent) {
    e.preventDefault();
    setError('');
    setSaving(true);
    try {
      // status só existe no DTO de update — o backend rejeita (whitelist) se
      // vier no create, então só entra no payload quando estamos editando.
      const { status, ...rest } = form;
      const payload = Object.fromEntries(
        Object.entries(editId ? form : rest)
          .filter(([, v]) => v !== '')
          .map(([k, v]) => [k, k === 'document' ? String(v).replace(/\D/g, '') : v]),
      );
      if (editId) {
        await api.put(`/clients/${editId}`, payload);
      } else {
        await api.post('/clients', payload);
      }
      setOpen(false);
      setEditId(null);
      load();
    } catch (err: any) {
      setError(err.response?.data?.message ?? 'Erro ao salvar cliente');
    } finally {
      setSaving(false);
    }
  }

  return (
    <>
      <input
        ref={xlsxInputRef}
        type="file"
        accept=".xlsx,.xls,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
        className="hidden"
        onChange={handleXlsxFile}
      />

      <Header
        title="Clientes"
        subtitle="Gerencie os tomadores de serviço"
        action={
          <div className="flex items-center gap-2">
            <button className="btn-secondary text-xs" onClick={downloadTemplate}>
              Baixar modelo
            </button>
            <button className="btn-secondary" onClick={() => xlsxInputRef.current?.click()}>
              Importar XLSX
            </button>
            <button className="btn-primary" onClick={openModal}>+ Novo cliente</button>
          </div>
        }
      />

      <div className="bg-white rounded-xl border border-[#EAE4D9] overflow-x-auto">
        {loading ? (
          <p className="p-6 text-sm text-[#0E0F12]/50">Carregando...</p>
        ) : items.length === 0 ? (
          <p className="p-6 text-sm text-[#0E0F12]/50">Nenhum cliente cadastrado ainda.</p>
        ) : (
          <table className="w-full text-sm">
            <thead className="bg-[#FAF7F2] border-b border-[#EAE4D9]">
              <tr>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Nome</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Tipo</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Documento</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">E-mail</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Endereço</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Status</th>
                <th className="px-6 py-3" />
              </tr>
            </thead>
            <tbody className="divide-y divide-[#EAE4D9]">
              {items.map((c) => (
                <tr key={c.id} className="hover:bg-[#FAF7F2]">
                  <td className="px-6 py-3 font-medium text-[#0E0F12]">{c.name}</td>
                  <td className="px-6 py-3 text-[#0E0F12]/50">{c.type}</td>
                  <td className="px-6 py-3 text-[#0E0F12]/50">{c.document ?? '—'}</td>
                  <td className="px-6 py-3 text-[#0E0F12]/50">{(c as any).emailCommercial ?? c.email ?? '—'}</td>
                  <td className="px-6 py-3 text-[#0E0F12]/50 text-xs">
                    {(c as any).address
                      ? `${(c as any).address}, ${(c as any).addressNumber ?? ''} — ${(c as any).uf ?? ''}`
                      : <span className="text-orange-400">Sem endereço</span>}
                  </td>
                  <td className="px-6 py-3"><StatusBadge status={c.status} /></td>
                  <td className="px-6 py-3 text-right">
                    <div className="flex items-center justify-end gap-2">
                      <button
                        onClick={() => setClienteCompras(c)}
                        className="text-xs px-3 py-1.5 rounded-lg border border-[#EAE4D9] text-[#B7895A] hover:bg-[#FAF7F2] transition-colors"
                      >
                        Compras
                      </button>
                      <button
                        onClick={() => openEdit(c)}
                        className="text-xs px-3 py-1.5 rounded-lg border border-[#EAE4D9] text-[#0E0F12]/60 hover:bg-[#FAF7F2] transition-colors"
                      >
                        Editar
                      </button>
                      <button
                        onClick={() => handleInactivate(c.id, c.name)}
                        disabled={inactivating === c.id}
                        className="text-xs px-3 py-1.5 rounded-lg border border-red-200 text-red-500 hover:bg-red-50 disabled:opacity-50 transition-colors"
                      >
                        {inactivating === c.id ? '...' : 'Inativar'}
                      </button>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      {xlsxCnpjs && (
        <XlsxPreviewModal
          cnpjs={xlsxCnpjs}
          onClose={() => setXlsxCnpjs(null)}
          onDone={() => { setXlsxCnpjs(null); load(); }}
        />
      )}

      {clienteCompras && (
        <ContratosModal
          client={clienteCompras as any}
          onClose={() => setClienteCompras(null)}
        />
      )}

      <Modal open={open} onClose={() => setOpen(false)} title={editId ? 'Editar cliente' : 'Novo cliente'} wide>
        <form onSubmit={handleSubmit} className="space-y-4">
          {error && <div className="bg-red-50 text-red-700 text-sm px-4 py-3 rounded-lg">{error}</div>}

          <div className="grid grid-cols-2 gap-3">
            <div>
              <label className="block text-sm font-medium text-[#0E0F12] mb-1">Tipo</label>
              <select className="input" value={form.type} onChange={(e) => set('type', e.target.value)}>
                <option value="PJ">Pessoa Jurídica (PJ)</option>
                <option value="PF">Pessoa Física (PF)</option>
              </select>
            </div>
            <div>
              <label className="block text-sm font-medium text-[#0E0F12] mb-1">
                {form.type === 'PJ' ? 'CNPJ' : 'CPF'}
                {cnpjLoading && <span className="ml-2 text-xs text-[#B7895A]">buscando...</span>}
              </label>
              <input
                className="input"
                value={form.document}
                onChange={(e) => set('document', e.target.value)}
                placeholder={form.type === 'PJ' ? '00000000000000' : '00000000000'}
                maxLength={18}
              />
            </div>
          </div>

          <div>
            <label className="block text-sm font-medium text-[#0E0F12] mb-1">Nome / Razão social <span className="text-red-500">*</span></label>
            <input className="input" required minLength={2} value={form.name} onChange={(e) => set('name', e.target.value)} placeholder="Empresa ABC Ltda" />
          </div>

          <div className="grid grid-cols-3 gap-3">
            <div className="col-span-2">
              <label className="block text-sm font-medium text-[#0E0F12] mb-1">Endereço</label>
              <input className="input" value={form.address} onChange={(e) => set('address', e.target.value)} placeholder="Rua das Flores" />
            </div>
            <div>
              <label className="block text-sm font-medium text-[#0E0F12] mb-1">Número</label>
              <input className="input" value={form.addressNumber} onChange={(e) => set('addressNumber', e.target.value)} placeholder="123" />
            </div>
          </div>

          <div className="grid grid-cols-3 gap-3">
            <div>
              <label className="block text-sm font-medium text-[#0E0F12] mb-1">
                CEP
                {cepLoading && <span className="ml-2 text-xs text-[#B7895A]">buscando...</span>}
              </label>
              <input
                className="input"
                value={form.zipCode}
                onChange={(e) => { set('zipCode', e.target.value); handleCepChange(e.target.value); }}
                placeholder="00000000"
                maxLength={8}
              />
            </div>
            <div>
              <label className="block text-sm font-medium text-[#0E0F12] mb-1">Bairro</label>
              <input className="input" value={form.neighborhood} onChange={(e) => set('neighborhood', e.target.value)} />
            </div>
            <div>
              <label className="block text-sm font-medium text-[#0E0F12] mb-1">UF</label>
              <input className="input" value={form.uf} onChange={(e) => set('uf', e.target.value)} placeholder="SP" maxLength={2} />
            </div>
          </div>

          <div className="border-t border-[#EAE4D9] pt-4">
            <p className="text-xs font-semibold text-[#0E0F12]/40 uppercase tracking-wide mb-3">Contato</p>
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-sm font-medium text-[#0E0F12] mb-1">Telefone comercial</label>
                <input className="input" value={form.phoneCommercial} onChange={(e) => set('phoneCommercial', e.target.value)} placeholder="(11) 99999-9999" />
              </div>
              <div>
                <label className="block text-sm font-medium text-[#0E0F12] mb-1">Telefone financeiro</label>
                <input className="input" value={form.phoneFinancial} onChange={(e) => set('phoneFinancial', e.target.value)} placeholder="(11) 99999-9999" />
              </div>
            </div>
            <div className="grid grid-cols-3 gap-3 mt-3">
              <div>
                <label className="block text-sm font-medium text-[#0E0F12] mb-1">Email comercial</label>
                <input className="input" type="email" value={form.emailCommercial} onChange={(e) => set('emailCommercial', e.target.value)} placeholder="comercial@empresa.com" />
              </div>
              <div>
                <label className="block text-sm font-medium text-[#0E0F12] mb-1">Email financeiro</label>
                <input className="input" type="email" value={form.emailFinancial} onChange={(e) => set('emailFinancial', e.target.value)} placeholder="financeiro@empresa.com" />
              </div>
              <div>
                <label className="block text-sm font-medium text-[#0E0F12] mb-1">Email para envio de NF</label>
                <input className="input" type="email" value={form.emailNf} onChange={(e) => set('emailNf', e.target.value)} placeholder="nf@empresa.com" />
              </div>
            </div>
          </div>

          {editId && (
            <div className="border-t border-gray-100 pt-4">
              <p className="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-3">Status</p>
              <select className="input w-48" value={form.status} onChange={(e) => set('status', e.target.value)}>
                <option value="active">Ativo</option>
                <option value="inactive">Inativo</option>
              </select>
            </div>
          )}

          <div className="flex justify-end gap-3 pt-2">
            <button type="button" className="btn-secondary" onClick={() => setOpen(false)}>Cancelar</button>
            <button type="submit" className="btn-primary" disabled={saving}>
              {saving ? 'Salvando...' : editId ? 'Salvar' : 'Criar cliente'}
            </button>
          </div>
        </form>
      </Modal>
    </>
  );
}

function StatusBadge({ status }: { status: string }) {
  const map: Record<string, string> = {
    active:   'bg-green-100 text-green-700',
    inactive: 'bg-[#EAE4D9] text-[#0E0F12]/60',
  };
  return (
    <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${map[status] ?? 'bg-[#EAE4D9] text-[#0E0F12]/60'}`}>
      {status}
    </span>
  );
}
