import Link from 'next/link';
import { api, isAdmin, me } from '@/lib/api';
import { date } from '@/lib/format';
import { Card, Empty, Flash, Forbidden, PageHeader, Pill, Tabs, type SP } from '@/components/ui';
import { SubmitButton } from '@/components/Actions';
import { AlertIcon, ArrowLeftIcon, CheckIcon, RefreshIcon } from '@/components/Icons';
import { retryDelivery } from '../../../actions';

type Row = { id: number; leadId: number; leadRef: string; status: string; attempts: number; lastError: string | null; createdAt: string; lawyerId: number; lawyer: string; organization: string | null; webhookUrl: string | null };

export default async function Deliveries({ searchParams }: { searchParams: SP }) {
  const sp = await searchParams;
  const viewer = await me();
  if (!isAdmin(viewer.role)) return <Forbidden what="lead deliveries" />;
  const status = sp.status === 'pending' ? 'pending' : 'failed';
  const d = await api<{ items: Row[] }>(`/admin/lead-deliveries?status=${status}`);
  return (
    <>
      <Link href="/leads" className="mb-3 inline-flex items-center gap-1.5 text-sm text-muted hover:text-ink">
        <ArrowLeftIcon className="h-4 w-4" /> All leads
      </Link>
      <PageHeader
        title="Webhook deliveries"
        icon={<AlertIcon className="h-5 w-5" />}
        description="Enquiries a firm’s CRM webhook didn’t accept. Failed ones exhausted 5 attempts (or hit a blocked or invalid address) — the lawyer can still see them in their dashboard. Fix the receiver, then retry."
        actions={
          <Tabs
            current={status}
            items={[
              { value: 'failed', label: 'Failed', href: '/leads/deliveries' },
              { value: 'pending', label: 'Retrying', href: '?status=pending' },
            ]}
          />
        }
      />
      <Flash ok={sp.ok} err={sp.err} />
      <Card>
        {d.items.length ? (
          <div className="overflow-x-auto">
            <table className="tbl">
              <thead>
                <tr>
                  <th>Lead</th>
                  <th>Lawyer / firm</th>
                  <th>Endpoint</th>
                  <th className="text-right">Attempts</th>
                  <th>Last error</th>
                  {status === 'failed' && <th />}
                </tr>
              </thead>
              <tbody>
                {d.items.map((r) => (
                  <tr key={r.id}>
                    <td>
                      <Link href={`/leads/${r.leadId}`} className="font-medium hover:text-ledger hover:underline">
                        {r.leadRef}
                      </Link>
                      <span className="block text-xs text-muted">{date(r.createdAt, true)}</span>
                    </td>
                    <td className="text-sm">
                      {r.lawyer}
                      <span className="block text-xs text-muted">{r.organization ?? 'no organization'}</span>
                    </td>
                    <td className="max-w-[16rem] truncate text-xs" title={r.webhookUrl ?? ''}>
                      {r.webhookUrl ?? <Pill value="no webhook" tone="warn" />}
                    </td>
                    <td className="num text-right">{r.attempts}</td>
                    <td className="max-w-xs text-xs text-danger">{r.lastError}</td>
                    {status === 'failed' && (
                      <td>
                        <form action={retryDelivery}>
                          <input type="hidden" name="id" value={r.id} />
                          <SubmitButton className="btn btn-quiet btn-xs" disabled={!r.webhookUrl}>
                            <RefreshIcon className="h-3.5 w-3.5" /> Retry
                          </SubmitButton>
                        </form>
                      </td>
                    )}
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        ) : (
          <Empty icon={<CheckIcon className="h-6 w-6" />}>{status === 'failed' ? 'No failed deliveries.' : 'Nothing is retrying right now.'}</Empty>
        )}
      </Card>
    </>
  );
}
