---
import CrmLayout from '@/layouts/CrmLayout.astro';
import { contacts, companies, opportunities, quotes } from '@/lib/crm/store';
import { formatMxn, formatDate } from '@/lib/util/format';

export const prerender = false;

const onlyDeleted = (arr: { deletedAt: string | null }[]) => arr.filter((r) => r.deletedAt);

const groups = [
  { key: 'contacts', label: 'Contactos / Leads', api: '/api/crm/contacts', rows: onlyDeleted(contacts.list(true)).map((c: any) => ({ id: c.id, main: c.fullName, sub: c.email ?? '—', at: c.deletedAt })) },
  { key: 'companies', label: 'Empresas', api: '/api/crm/companies', rows: onlyDeleted(companies.list(true)).map((c: any) => ({ id: c.id, main: c.name, sub: c.rfc ?? '—', at: c.deletedAt })) },
  { key: 'opportunities', label: 'Oportunidades', api: '/api/crm/opportunities', rows: onlyDeleted(opportunities.list(true)).map((o: any) => ({ id: o.id, main: o.title, sub: formatMxn(o.amountEstimated), at: o.deletedAt })) },
  { key: 'quotes', label: 'Cotizaciones', api: '/api/crm/quotes', rows: onlyDeleted(quotes.list(true)).map((q: any) => ({ id: q.id, main: q.folio, sub: formatMxn(q.total), at: q.deletedAt })) },
];
const total = groups.reduce((s, g) => s + g.rows.length, 0);
---

<CrmLayout title="Archivados · CRM">
  <h1>Archivados</h1>
  <p class="muted">{total} registros archivados (soft delete). Puedes restaurarlos; la eliminación definitiva queda para super_admin/mantenimiento.</p>

  {total === 0 && <p class="notice" style="margin-top:16px">No hay registros archivados.</p>}

  {
    groups.filter((g) => g.rows.length > 0).map((g) => (
      <section style="margin-top:22px">
        <h2 style="font-size:1.1rem">{g.label} ({g.rows.length})</h2>
        <div class="table-wrap" style="margin-top:10px">
          <table class="data">
            <thead><tr><th>Registro</th><th>Detalle</th><th>Archivado</th><th></th></tr></thead>
            <tbody>
              {g.rows.map((r) => (
                <tr>
                  <td>{r.main}</td>
                  <td>{r.sub}</td>
                  <td>{formatDate(r.at)}</td>
                  <td><button class="chip act-restore" style="cursor:pointer" data-url={`${g.api}/${r.id}/restore`}>↺ Restaurar</button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </section>
    ))
  }

  <script>
    document.querySelectorAll<HTMLButtonElement>('.act-restore').forEach((b) => {
      b.addEventListener('click', async () => {
        b.disabled = true;
        const res = await fetch(b.dataset.url!, { method: 'POST' });
        if ((await res.json()).ok) location.reload();
        else b.disabled = false;
      });
    });
  </script>
</CrmLayout>
