'use client';

import { useEffect, useState, FormEvent, useMemo } from 'react';
import Header from '@/components/header';
import Modal from '@/components/modal';
import ServiceListSelect from '@/components/service-list-select';
import api from '@/lib/api';
import { Invoice, Charge, Client } from '@/types';

const STATUS_COLORS: Record<string, string> = {
  pending:   'bg-yellow-100 text-yellow-700',
  queued:    'bg-blue-100 text-blue-700',
  issued:    'bg-green-100 text-green-700',
  cancelled: 'bg-[#EAE4D9] text-[#0E0F12]/60',
  error:     'bg-red-100 text-red-700',
};
const STATUS_LABELS: Record<string, string> = {
  pending: 'Pendente', queued: 'Na fila', issued: 'Emitida',
  cancelled: 'Cancelada', error: 'Erro',
};
const EXIGIBILITY_OPTIONS = [
  { value: 1, label: '1 — Exigível' },
  { value: 2, label: '2 — Não incidência' },
  { value: 3, label: '3 — Isenção' },
  { value: 4, label: '4 — Exportação' },
  { value: 5, label: '5 — Imunidade' },
  { value: 6, label: '6 — Exig. suspensa — Decisão Judicial' },
  { value: 7, label: '7 — Exig. suspensa — Proc. Administrativo' },
];

const today = () => new Date().toISOString().slice(0, 10);

const EMPTY_FORM = {
  issAliquota: '',
  issRetained: false,
  serviceListItem: '',
  discrimination: '',
  issExigibility: '1',
  competenceDate: today(),
};

type BulkRow = {
  chargeId: string;
  label: string;
  status: 'pending' | 'emitting' | 'done' | 'error';
  error?: string;
};

export default function NotasFiscaisPage() {
  const [items, setItems]     = useState<Invoice[]>([]);
  const [charges, setCharges] = useState<Charge[]>([]);
  const [clients, setClients] = useState<Client[]>([]);
  const [loading, setLoading] = useState(true);
  const [open, setOpen]       = useState(false);
  const [form, setForm]       = useState(EMPTY_FORM);
  const [search, setSearch]   = useState('');
  const [selected, setSelected] = useState<Set<string>>(new Set());
  const [bulkRows, setBulkRows] = useState<BulkRow[] | null>(null);
  const [running, setRunning]   = useState(false);
  const [retryLoading, setRetryLoading] = useState<string | null>(null);
  const [consultarLoading, setConsultarLoading] = useState<string | null>(null);
  const [emailLoading, setEmailLoading] = useState<string | null>(null);
  const [syncLoading, setSyncLoading] = useState(false);
  const [retryModal, setRetryModal] = useState<{ id: string; rpsNumber: number } | null>(null);
  const [retryRps, setRetryRps] = useState('');
  const [rpsSeq, setRpsSeq] = useState<number | null>(null);
  const [rpsEditOpen, setRpsEditOpen] = useState(false);
  const [rpsNewVal, setRpsNewVal] = useState('');
  const [rpsSaving, setRpsSaving] = useState(false);

  function load() {
    setLoading(true);
    api.get('/invoices').then((r) => setItems(r.data.data ?? r.data)).catch(() => {}).finally(() => setLoading(false));
  }

  useEffect(() => {
    load();
    api.get('/charges').then((r) => setCharges((r.data.data ?? r.data).filter((c: Charge) => c.status !== 'cancelled'))).catch(() => {});
    api.get('/clients').then((r) => setClients(r.data.data ?? r.data)).catch(() => {});
    api.get('/invoices/rps-sequence').then((r) => setRpsSeq(r.data.current)).catch(() => {});
  }, []);

  async function handleSaveRpsSeq() {
    const nextRps = parseInt(rpsNewVal, 10);
    if (isNaN(nextRps) || nextRps < 1) { alert('Informe um número válido ≥ 1'); return; }
    // last_value = próximo − 1, pois nextRpsNumber() faz last_value + 1 antes de usar
    const lastValue = nextRps - 1;
    setRpsSaving(true);
    try {
      await api.patch('/invoices/rps-sequence', { value: lastValue });
      setRpsSeq(lastValue);
      setRpsEditOpen(false);
    } catch (err: any) {
      alert(err.response?.data?.message ?? 'Erro ao atualizar sequência');
    } finally {
      setRpsSaving(false);
    }
  }

  function setF(field: string, value: string | boolean) { setForm((p) => ({ ...p, [field]: value })); }

  function toggleCharge(id: string) {
    setSelected((prev) => {
      const next = new Set(prev);
      next.has(id) ? next.delete(id) : next.add(id);
      return next;
    });
  }

  function toggleAll(filtered: Charge[]) {
    const ids = filtered.map((c) => c.id);
    const allSel = ids.every((id) => selected.has(id));
    setSelected((prev) => {
      const next = new Set(prev);
      allSel ? ids.forEach((id) => next.delete(id)) : ids.forEach((id) => next.add(id));
      return next;
    });
  }

  const chargesWithActiveInvoice = useMemo(
    () => new Set(items.filter((i) => i.status !== 'cancelled').map((i) => i.chargeId).filter(Boolean)),
    [items],
  );

  const filteredCharges = useMemo(
    () => charges.filter((c) => {
      if (chargesWithActiveInvoice.has(c.id)) return false;
      const clientName = clients.find((cl) => cl.id === c.clientId)?.name ?? '';
      return (
        c.number.toLowerCase().includes(search.toLowerCase()) ||
        clientName.toLowerCase().includes(search.toLowerCase()) ||
        (c.description ?? '').toLowerCase().includes(search.toLowerCase())
      );
    }),
    [charges, clients, search, chargesWithActiveInvoice],
  );

  const allFilteredSelected =
    filteredCharges.length > 0 && filteredCharges.every((c) => selected.has(c.id));

  function openModal() {
    setForm({ ...EMPTY_FORM, competenceDate: today() });
    setSearch('');
    setSelected(new Set());
    setBulkRows(null);
    setRunning(false);
    setOpen(true);
  }

  function closeModal() {
    if (running) return;
    setOpen(false);
  }

  async function handleSubmit(e: FormEvent) {
    e.preventDefault();
    if (selected.size === 0) return;

    const rows: BulkRow[] = [...selected].map((id) => {
      const charge = charges.find((c) => c.id === id);
      const clientName = clients.find((cl) => cl.id === charge?.clientId)?.name ?? '—';
      return {
        chargeId: id,
        label: `${charge?.number ?? id} — ${clientName} — R$ ${Number(charge?.amount ?? 0).toFixed(2)}`,
        status: 'pending',
      };
    });
    setBulkRows(rows);
    setRunning(true);

    for (let i = 0; i < rows.length; i++) {
      setBulkRows((prev) => prev!.map((r, j) => j === i ? { ...r, status: 'emitting' } : r));
      try {
        const payload: any = {
          chargeId:        rows[i].chargeId,
          issAliquota:     form.issAliquota ? Number(form.issAliquota) : undefined,
          issRetained:     form.issRetained,
          serviceListItem: form.serviceListItem,
          discrimination:  form.discrimination,
          issExigibility:  Number(form.issExigibility),
          competenceDate:  form.competenceDate,
        };
        await api.post('/invoices', payload);
        setBulkRows((prev) => prev!.map((r, j) => j === i ? { ...r, status: 'done' } : r));
      } catch (err: any) {
        const msg = err.response?.data?.message ?? 'Erro';
        setBulkRows((prev) => prev!.map((r, j) => j === i ? { ...r, status: 'error', error: msg } : r));
      }
    }

    setRunning(false);
    load();
  }

  const done    = bulkRows?.filter((r) => r.status === 'done').length ?? 0;
  const errors  = bulkRows?.filter((r) => r.status === 'error').length ?? 0;
  const allDone = bulkRows?.every((r) => r.status === 'done' || r.status === 'error') ?? false;

  function openRetryModal(inv: Invoice) {
    const e10 = inv.errorMessage?.match(/Pr[oó]ximo RPS V[aá]lido:\s*(\d+)/i);
    const suggested = e10 ? parseInt(e10[1], 10) : inv.rpsNumber;
    setRetryRps(String(suggested));
    setRetryModal({ id: inv.id, rpsNumber: inv.rpsNumber });
  }

  async function confirmRetry() {
    if (!retryModal) return;
    const newRps = parseInt(retryRps, 10);
    setRetryLoading(retryModal.id);
    try {
      const body = !isNaN(newRps) && newRps !== retryModal.rpsNumber ? { rpsNumber: newRps } : {};
      await api.post(`/invoices/${retryModal.id}/retry`, body);
      setRetryModal(null);
      load();
    } catch (err: any) {
      alert(err?.response?.data?.message ?? 'Erro ao retransmitir NFS-e');
    } finally {
      setRetryLoading(null);
    }
  }

  async function handleConsultar(invoiceId: string) {
    setConsultarLoading(invoiceId);
    try {
      await api.post(`/invoices/${invoiceId}/consultar`);
      load();
    } catch (err: any) {
      alert(err?.response?.data?.message ?? 'Erro ao consultar NFS-e na prefeitura');
    } finally {
      setConsultarLoading(null);
    }
  }

  function handlePdf(invoiceId: string) {
    window.open(`/notas-fiscais/${invoiceId}`, '_blank');
  }

  async function handleSendEmail(invoiceId: string) {
    setEmailLoading(invoiceId);
    try {
      await api.post(`/invoices/${invoiceId}/send-email`);
      load();
    } catch (err: any) {
      alert(err?.response?.data?.message ?? 'Erro ao enviar e-mail');
    } finally {
      setEmailLoading(null);
    }
  }

  async function handleSync() {
    setSyncLoading(true);
    try {
      const r = await api.post('/invoices/sync');
      const { total, updated, errors: errs } = r.data;
      alert(`Sincronização concluída.\n${total} nota(s) verificada(s) · ${updated} atualizada(s)${errs > 0 ? ` · ${errs} erro(s)` : ''}`);
      load();
    } catch (err: any) {
      alert(err?.response?.data?.message ?? 'Erro ao sincronizar notas');
    } finally {
      setSyncLoading(false);
    }
  }

  const chargeStatusLabel: Record<string, string> = { pending: 'Pendente', paid: 'Paga', overdue: 'Vencida' };
  const chargeStatusColor: Record<string, string> = { pending: 'text-yellow-600', paid: 'text-green-600', overdue: 'text-red-600' };

  return (
    <>
      <Header
        title="NFS-e"
        subtitle="Notas fiscais de serviço eletrônicas"
        action={
          <div className="flex items-center gap-3">
            {rpsSeq !== null && (
              <div className="flex items-center gap-1.5 text-xs text-[#0E0F12]/50 bg-[#FAF7F2] border border-[#EAE4D9] rounded-lg px-3 py-1.5">
                <span>Próximo RPS: <span className="font-semibold text-[#0E0F12]">#{rpsSeq + 1}</span></span>
                <button
                  onClick={() => { setRpsNewVal(String(rpsSeq + 1)); setRpsEditOpen(true); }}
                  className="text-[#B7895A] hover:text-[#9E7248] ml-1 font-medium"
                  title="Corrigir sequência RPS para alinhar com o portal da prefeitura"
                >
                  Corrigir
                </button>
              </div>
            )}
            <button
              className="btn-secondary text-sm"
              onClick={handleSync}
              disabled={syncLoading}
              title="Consulta a prefeitura e atualiza NFS-e emitidas e notas na fila"
            >
              {syncLoading ? 'Sincronizando…' : 'Sincronizar'}
            </button>
            <button className="btn-primary" onClick={openModal}>+ Emitir NFS-e</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">Nenhuma nota fiscal emitida 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">RPS</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">NFS-e</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Tomador</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Competência</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Valor</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">Status</th>
                <th className="text-left px-6 py-3 font-medium text-[#0E0F12]/60">E-mail</th>
                <th className="px-6 py-3" />
              </tr>
            </thead>
            <tbody className="divide-y divide-[#EAE4D9]">
              {items.map((i) => (
                <tr key={i.id} className="hover:bg-[#FAF7F2]">
                  <td className="px-6 py-3 font-medium text-[#0E0F12]">{i.rpsNumber}</td>
                  <td className="px-6 py-3 text-[#0E0F12]/50">{i.nfseNumber ?? '—'}</td>
                  <td className="px-6 py-3 text-[#0E0F12]">{clients.find((c) => c.id === i.clientId)?.name ?? '—'}</td>
                  <td className="px-6 py-3 text-[#0E0F12]/50">{i.competenceDate ?? '—'}</td>
                  <td className="px-6 py-3 text-[#0E0F12]">R$ {Number(i.serviceAmount).toFixed(2)}</td>
                  <td className="px-6 py-3">
                    <span className={`px-2 py-0.5 rounded-full text-xs font-medium ${STATUS_COLORS[i.status] ?? 'bg-[#EAE4D9] text-[#0E0F12]/60'}`}>
                      {STATUS_LABELS[i.status] ?? i.status}
                    </span>
                    {i.errorMessage && (i.status === 'error' || i.status === 'queued') && (
                      <p className={`text-xs mt-1 max-w-md whitespace-pre-wrap break-words ${i.status === 'error' ? 'text-red-500' : 'text-blue-500'}`}>
                        {i.errorMessage}
                      </p>
                    )}
                  </td>
                  <td className="px-6 py-3">
                    {i.emailSentAt ? (
                      <span className="text-xs text-green-600 font-medium" title={`Enviado em ${new Date(i.emailSentAt).toLocaleString('pt-BR')}`}>
                        ✓ {new Date(i.emailSentAt).toLocaleDateString('pt-BR')}
                      </span>
                    ) : (
                      <span className="text-xs text-[#0E0F12]/40">—</span>
                    )}
                  </td>
                  <td className="px-6 py-3 text-right space-x-3">
                    {i.status === 'queued' && (
                      <button
                        onClick={() => handleConsultar(i.id)}
                        disabled={consultarLoading === i.id}
                        className="text-xs font-medium text-blue-500 hover:text-blue-700 disabled:opacity-40"
                      >
                        {consultarLoading === i.id ? '…' : 'Consultar'}
                      </button>
                    )}
                    {(i.status === 'error' || i.status === 'queued') && (
                      <button
                        onClick={() => openRetryModal(i)}
                        disabled={retryLoading === i.id}
                        className="text-xs font-medium text-orange-500 hover:text-orange-700 disabled:opacity-40"
                      >
                        {retryLoading === i.id ? '…' : 'Retransmitir'}
                      </button>
                    )}
                    {i.status === 'issued' && (
                      <button
                        onClick={() => handleSendEmail(i.id)}
                        disabled={emailLoading === i.id}
                        className="text-xs font-medium text-emerald-600 hover:text-emerald-800 disabled:opacity-40"
                        title={i.emailSentAt ? `Reenviar (último envio: ${new Date(i.emailSentAt).toLocaleString('pt-BR')})` : 'Enviar por e-mail ao tomador'}
                      >
                        {emailLoading === i.id ? '…' : i.emailSentAt ? 'Reenviar' : 'Enviar'}
                      </button>
                    )}
                    <button
                      onClick={() => handlePdf(i.id)}
                      className="text-xs font-medium text-[#B7895A] hover:text-[#9E7248]"
                    >
                      PDF
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}
      </div>

      <Modal open={rpsEditOpen} onClose={() => setRpsEditOpen(false)} title="Corrigir sequência RPS">
        <div className="space-y-4">
          <p className="text-sm text-[#0E0F12]/60">
            Informe o número do <strong>próximo RPS</strong> que a prefeitura espera receber.
            Consulte o portal da prefeitura para verificar o último RPS aceito e some 1.
          </p>
          <p className="text-sm text-[#0E0F12]/50">
            Sequência atual na plataforma: próximo seria <strong>#{rpsSeq !== null ? rpsSeq + 1 : '—'}</strong>
          </p>
          <div>
            <label className="block text-sm font-medium text-[#0E0F12] mb-1">Próximo RPS <span className="text-red-500">*</span></label>
            <input
              className="input"
              type="number"
              min="1"
              value={rpsNewVal}
              onChange={(e) => setRpsNewVal(e.target.value)}
              placeholder="Ex: 42"
            />
            <p className="text-xs text-[#0E0F12]/40 mt-1">
              A sequência será ajustada para que o próximo RPS emitido use este número.
              O valor salvo será {rpsNewVal ? Number(rpsNewVal) - 1 : '—'} (last_value = próximo − 1).
            </p>
          </div>
          <div className="flex justify-end gap-3 pt-1">
            <button className="btn-secondary" onClick={() => setRpsEditOpen(false)} disabled={rpsSaving}>Cancelar</button>
            <button className="btn-primary" onClick={handleSaveRpsSeq} disabled={rpsSaving}>
              {rpsSaving ? 'Salvando...' : 'Salvar'}
            </button>
          </div>
        </div>
      </Modal>

      <Modal open={!!retryModal} onClose={() => { if (retryLoading) return; setRetryModal(null); }} title="Retransmitir NFS-e">
        <div className="space-y-4">
          <p className="text-sm text-[#0E0F12]/50">
            RPS original: <span className="font-medium text-[#0E0F12]">#{retryModal?.rpsNumber}</span>.
            {retryModal && parseInt(retryRps, 10) !== retryModal.rpsNumber && (
              <span className="text-blue-600"> Próximo válido indicado pela prefeitura: #{retryRps}.</span>
            )}
          </p>
          <div>
            <label className="block text-sm font-medium text-[#0E0F12] mb-1">Número do RPS</label>
            <input
              className="input"
              type="number"
              min="1"
              value={retryRps}
              onChange={(e) => setRetryRps(e.target.value)}
            />
          </div>
          <div className="flex justify-end gap-3 pt-1">
            <button
              className="btn-secondary"
              onClick={() => setRetryModal(null)}
              disabled={!!retryLoading}
            >
              Cancelar
            </button>
            <button
              className="btn-primary"
              onClick={confirmRetry}
              disabled={!!retryLoading}
            >
              {retryLoading ? '…' : 'Retransmitir'}
            </button>
          </div>
        </div>
      </Modal>

      <Modal open={open} onClose={closeModal} title="Emitir NFS-e" wide>
        {!bulkRows ? (
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-sm font-medium text-[#0E0F12] mb-1">Competência <span className="text-red-500">*</span></label>
                <input className="input" type="date" required value={form.competenceDate} onChange={(e) => setF('competenceDate', e.target.value)} />
              </div>
              <div>
                <label className="block text-sm font-medium text-[#0E0F12] mb-1">Exigibilidade ISS</label>
                <select className="input" value={form.issExigibility} onChange={(e) => setF('issExigibility', e.target.value)}>
                  {EXIGIBILITY_OPTIONS.map((o) => (
                    <option key={o.value} value={o.value}>{o.label}</option>
                  ))}
                </select>
              </div>
            </div>

            <div>
              <label className="block text-sm font-medium text-[#0E0F12] mb-1">Item lista serviço (LC 116) <span className="text-red-500">*</span></label>
              <ServiceListSelect value={form.serviceListItem} onChange={(v) => setF('serviceListItem', v)} />
            </div>

            <div>
              <label className="block text-sm font-medium text-[#0E0F12] mb-1">Discriminação do serviço <span className="text-red-500">*</span></label>
              <textarea
                className="input resize-none"
                rows={3}
                required
                minLength={5}
                value={form.discrimination}
                onChange={(e) => setF('discrimination', e.target.value)}
                placeholder="Descreva os serviços prestados..."
              />
            </div>

            <div className="grid grid-cols-2 gap-3">
              <div>
                <label className="block text-sm font-medium text-[#0E0F12] mb-1">Alíquota ISS (%)</label>
                <input className="input" type="number" min="0" max="100" step="0.01" value={form.issAliquota} onChange={(e) => setF('issAliquota', e.target.value)} placeholder="5.00" />
              </div>
              <div className="flex items-end pb-1.5">
                <label className="flex items-center gap-2 text-sm text-[#0E0F12] cursor-pointer">
                  <input type="checkbox" className="h-4 w-4 rounded border-[#EAE4D9] accent-[#B7895A]" checked={form.issRetained} onChange={(e) => setF('issRetained', e.target.checked)} />
                  ISS retido pelo tomador
                </label>
              </div>
            </div>

            {/* Charge multi-select */}
            <div>
              <div className="flex items-center justify-between mb-1">
                <label className="text-sm font-medium text-[#0E0F12]">
                  Cobranças <span className="text-red-500">*</span>
                  {selected.size > 0 && (
                    <span className="ml-2 text-xs font-normal text-[#B7895A]">
                      {selected.size} selecionada{selected.size !== 1 ? 's' : ''}
                    </span>
                  )}
                </label>
                {filteredCharges.length > 0 && (
                  <button
                    type="button"
                    onClick={() => toggleAll(filteredCharges)}
                    className="text-xs text-[#B7895A] hover:text-[#9E7248]"
                  >
                    {allFilteredSelected ? 'Desmarcar todas' : 'Selecionar todas'}
                  </button>
                )}
              </div>
              <input
                className="input mb-2"
                placeholder="Buscar por número, cliente ou descrição..."
                value={search}
                onChange={(e) => setSearch(e.target.value)}
              />
              <div className="border border-[#EAE4D9] rounded-lg overflow-y-auto max-h-48 divide-y divide-[#EAE4D9]">
                {filteredCharges.length === 0 ? (
                  <p className="px-4 py-3 text-sm text-[#0E0F12]/40">Nenhuma cobrança encontrada.</p>
                ) : (
                  filteredCharges.map((c) => {
                    const clientName = clients.find((cl) => cl.id === c.clientId)?.name ?? '—';
                    return (
                      <label
                        key={c.id}
                        className="flex items-center gap-3 px-4 py-2.5 hover:bg-[#FAF7F2] cursor-pointer"
                      >
                        <input
                          type="checkbox"
                          className="h-4 w-4 rounded border-[#EAE4D9] accent-[#B7895A] shrink-0"
                          checked={selected.has(c.id)}
                          onChange={() => toggleCharge(c.id)}
                        />
                        <div className="flex-1 min-w-0">
                          <span className="text-sm text-[#0E0F12] font-medium">{c.number}</span>
                          <span className="text-sm text-[#0E0F12]/50 ml-2">{clientName}</span>
                          {c.description && (
                            <span className="text-xs text-[#0E0F12]/40 block truncate">{c.description}</span>
                          )}
                        </div>
                        <div className="text-right shrink-0">
                          <span className="text-sm text-[#0E0F12]">R$ {Number(c.amount).toFixed(2)}</span>
                          <span className={`block text-xs ${chargeStatusColor[c.status] ?? 'text-[#0E0F12]/50'}`}>
                            {chargeStatusLabel[c.status] ?? c.status}
                          </span>
                        </div>
                      </label>
                    );
                  })
                )}
              </div>
            </div>

            <div className="flex justify-end gap-3 pt-2">
              <button type="button" className="btn-secondary" onClick={closeModal}>Cancelar</button>
              <button type="submit" className="btn-primary" disabled={selected.size === 0}>
                Emitir {selected.size > 1 ? `${selected.size} NFS-e` : 'NFS-e'}
              </button>
            </div>
          </form>
        ) : (
          /* Progress view */
          <div className="space-y-4">
            <p className="text-sm text-[#0E0F12]/50">
              {allDone
                ? `Concluído: ${done} emitida${done !== 1 ? 's' : ''}${errors > 0 ? `, ${errors} erro${errors !== 1 ? 's' : ''}` : ''}.`
                : `Emitindo NFS-e para ${bulkRows.length} cobrança${bulkRows.length !== 1 ? 's' : ''}...`}
            </p>

            <div className="border border-[#EAE4D9] rounded-lg overflow-y-auto max-h-64 divide-y divide-[#EAE4D9]">
              {bulkRows.map((r, i) => (
                <div key={i} className="flex items-center justify-between px-4 py-2.5">
                  <span className="text-sm text-[#0E0F12]">{r.label}</span>
                  <span className="text-xs ml-4 shrink-0">
                    {r.status === 'pending'  && <span className="text-[#0E0F12]/40">—</span>}
                    {r.status === 'emitting' && <span className="text-[#B7895A]">emitindo...</span>}
                    {r.status === 'done'     && <span className="text-green-600 font-medium">OK</span>}
                    {r.status === 'error'    && (
                      <span className="text-red-600 text-right">
                        <span className="font-medium">Erro</span>
                        {r.error && <span className="block text-xs font-normal max-w-xs whitespace-pre-wrap break-words">{r.error}</span>}
                      </span>
                    )}
                  </span>
                </div>
              ))}
            </div>

            {allDone && (
              <div className="flex justify-end pt-1">
                <button className="btn-primary" onClick={closeModal}>Fechar</button>
              </div>
            )}
          </div>
        )}
      </Modal>
    </>
  );
}
