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

export const prerender = false;

const now = Date.now();
const all = tasks.list().map((t) => ({
  ...t,
  displayStatus:
    t.status === 'pending' && t.dueAt && new Date(t.dueAt).getTime() < now ? 'overdue' : t.status,
}));
all.sort((a, b) => (a.dueAt ?? '').localeCompare(b.dueAt ?? ''));

const oppTitle = (id: string | null) => (id ? opportunities.get(id)?.title ?? '—' : '—');
const contactName = (id: string | null) => (id ? contacts.get(id)?.fullName ?? '—' : '—');

const TYPE_LABEL: Record<string, string> = {
  call: 'Llamada', whatsapp: 'WhatsApp', email: 'Email', review_quote: 'Revisar cotización', follow_up: 'Seguimiento',
};
const STATUS_LABEL: Record<string, string> = {
  pending: 'Pendiente', overdue: 'Vencida', completed: 'Completada', cancelled: 'Cancelada',
};
const counts = {
  pending: all.filter((t) => t.displayStatus === 'pending').length,
  overdue: all.filter((t) => t.displayStatus === 'overdue').length,
  completed: all.filter((t) => t.displayStatus === 'completed').length,
};
---

<CrmLayout title="Tareas · CRM">
  <h1>Tareas</h1>
  <p class="muted">{all.length} tareas · {counts.pending} pendientes · <span style="color:var(--pf-danger,#ff7a8a)">{counts.overdue} vencidas</span> · {counts.completed} completadas</p>

  <div class="chips" style="margin:14px 0">
    <button class="chip active" data-f="todas">Todas</button>
    <button class="chip" data-f="pending">Pendientes</button>
    <button class="chip" data-f="overdue">Vencidas</button>
    <button class="chip" data-f="completed">Completadas</button>
  </div>

  {
    all.length === 0 ? (
      <p class="notice">Sin tareas. Se crean desde las oportunidades o las automatizaciones.</p>
    ) : (
      <div class="table-wrap">
        <table class="data" id="tasks-table">
          <thead>
            <tr><th>Tarea</th><th>Tipo</th><th>Oportunidad</th><th>Contacto</th><th>Vence</th><th>Estatus</th><th></th></tr>
          </thead>
          <tbody>
            {all.map((t) => (
              <tr data-status={t.displayStatus} data-id={t.id}>
                <td>{t.title}</td>
                <td>{TYPE_LABEL[t.type] ?? t.type}</td>
                <td>{t.opportunityId ? <a href={`/crm/oportunidades/${t.opportunityId}`} style="color:var(--pf-accent-300)">{oppTitle(t.opportunityId)}</a> : '—'}</td>
                <td>{contactName(t.contactId)}</td>
                <td>{formatDate(t.dueAt)}</td>
                <td style={t.displayStatus === 'overdue' ? 'color:var(--pf-danger,#ff7a8a);font-weight:600' : ''}>{STATUS_LABEL[t.displayStatus] ?? t.displayStatus}</td>
                <td style="white-space:nowrap">
                  {t.displayStatus !== 'completed' && <button class="chip act-complete" style="cursor:pointer">✓</button>}
                  <button class="chip act-delete" style="cursor:pointer">🗑</button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    )
  }

  <script>
    const rows = Array.from(document.querySelectorAll<HTMLElement>('#tasks-table tbody tr'));
    document.querySelectorAll<HTMLButtonElement>('.chips .chip').forEach((chip) => {
      chip.addEventListener('click', () => {
        document.querySelectorAll('.chips .chip').forEach((c) => c.classList.remove('active'));
        chip.classList.add('active');
        const f = chip.dataset.f;
        rows.forEach((r) => { r.style.display = f === 'todas' || r.dataset.status === f ? '' : 'none'; });
      });
    });

    document.querySelectorAll<HTMLButtonElement>('.act-complete').forEach((b) => {
      b.addEventListener('click', async () => {
        const id = b.closest('tr')!.dataset.id;
        const res = await fetch(`/api/crm/tasks/${id}/complete`, { method: 'POST' });
        if ((await res.json()).ok) location.reload();
      });
    });
    document.querySelectorAll<HTMLButtonElement>('.act-delete').forEach((b) => {
      b.addEventListener('click', async () => {
        if (!confirm('¿Eliminar esta tarea?')) return;
        const id = b.closest('tr')!.dataset.id;
        const res = await fetch(`/api/crm/tasks/${id}`, { method: 'DELETE' });
        if ((await res.json()).ok) location.reload();
      });
    });
  </script>
</CrmLayout>
