import type { Metadata } from 'next';
import Link from 'next/link';
import { getDb } from '@pintrush/db';
import { ButtonLink, buttonStyles } from '@/components/ui/Button';
import { formatDateTime, formatNumber } from '@/components/host/format';
import { EmptyState, linkStyles, Notice, PageHeader, Panel, StatusBadge, TableWrap, td, th } from '@/components/host/ui';
import { cn } from '@/lib/cn';
import { requireAdmin } from '@/lib/auth/session';
import { ADMIN_TZ, LEAD_STATUSES } from '../../_lib/constants';

export const metadata: Metadata = { title: 'Pilot leads' };

const PAGE_SIZE = 50;
type LeadStatus = (typeof LEAD_STATUSES)[number];

export default async function AdminLeadsPage({ searchParams }: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {
  await requireAdmin('/admin/leads');
  const sp = await searchParams;
  const rawStatus = typeof sp.status === 'string' ? sp.status : '';
  const status = (LEAD_STATUSES as readonly string[]).includes(rawStatus) ? (rawStatus as LeadStatus) : null;
  const page = Math.max(1, Math.min(1000, Math.floor(Number(sp.page) || 1)));
  const db = getDb();
  const where = status ? { status } : {};
  const [total, leads, byStatus] = await Promise.all([
    db.pilotLead.count({ where }),
    db.pilotLead.findMany({
      where,
      orderBy: { createdAt: 'desc' },
      skip: (page - 1) * PAGE_SIZE,
      take: PAGE_SIZE,
      select: { id: true, venueName: true, contactName: true, email: true, address: true, tvCount: true, status: true, createdAt: true },
    }),
    db.pilotLead.groupBy({ by: ['status'], _count: { _all: true } }),
  ]);
  const countFor = (s: LeadStatus) => byStatus.find((b) => b.status === s)?._count._all ?? 0;
  const all = byStatus.reduce((n, b) => n + b._count._all, 0);
  const pages = Math.max(1, Math.ceil(total / PAGE_SIZE));
  const filterHref = (s: LeadStatus | null, p = 1) => {
    const params = new URLSearchParams();
    if (s) params.set('status', s);
    if (p > 1) params.set('page', String(p));
    const qs = params.toString();
    return `/admin/leads${qs ? `?${qs}` : ''}`;
  };

  return (
    <div className="flex flex-col gap-8">
      <PageHeader
        title="Pilot leads"
        description="Applications from the /pilot form, newest first. Leads are kept until you delete them."
        actions={
          // A plain form POST (works without JavaScript): the route answers with a file download, so
          // the page stays put. POST-only so no link on another site can trigger an export.
          <form method="post" action="/admin/leads/export">
            {status && <input type="hidden" name="status" value={status} />}
            <button type="submit" className={buttonStyles({ variant: 'secondary' })}>
              Export CSV{status ? ` (${status.toLowerCase()})` : ''}
            </button>
          </form>
        }
      />
      {sp.deleted === '1' && <Notice tone="success">Lead deleted. Its contact details are gone for good.</Notice>}
      <nav aria-label="Filter by status" className="-mx-1 overflow-x-auto">
        <ul className="flex gap-2 px-1">
          {([null, ...LEAD_STATUSES] as const).map((s) => {
            const active = s === status;
            return (
              <li key={s ?? 'all'}>
                <Link
                  href={filterHref(s)}
                  aria-current={active ? 'page' : undefined}
                  className={cn(
                    'inline-flex min-h-11 items-center gap-2 rounded-xl border px-4 text-sm font-semibold whitespace-nowrap',
                    active ? 'border-violet bg-violet/20 text-fg' : 'border-line text-muted hover:border-violet-soft hover:text-fg',
                  )}
                >
                  {s ? s.charAt(0) + s.slice(1).toLowerCase() : 'All'}
                  <span className="num text-xs text-subtle">{formatNumber(s ? countFor(s) : all)}</span>
                </Link>
              </li>
            );
          })}
        </ul>
      </nav>
      <Panel padded={leads.length === 0}>
        {leads.length === 0 ? (
          <EmptyState title={status ? `No ${status.toLowerCase()} leads` : 'No pilot applications yet'}>Applications from the marketing site’s pilot form show up here.</EmptyState>
        ) : (
          <div className="px-5 sm:px-6">
            <TableWrap label="Pilot leads">
              <thead>
                <tr>
                  <th scope="col" className={th}>
                    Venue
                  </th>
                  <th scope="col" className={th}>
                    Contact
                  </th>
                  <th scope="col" className={th}>
                    TVs
                  </th>
                  <th scope="col" className={th}>
                    Status
                  </th>
                  <th scope="col" className={th}>
                    Received
                  </th>
                </tr>
              </thead>
              <tbody>
                {leads.map((l) => (
                  <tr key={l.id}>
                    <td className={td}>
                      <Link href={`/admin/leads/${l.id}`} className={linkStyles}>
                        {l.venueName}
                      </Link>
                      <span className="block max-w-xs truncate text-xs text-subtle">{l.address}</span>
                    </td>
                    <td className={td}>
                      {l.contactName}
                      <span className="block text-xs text-subtle">{l.email}</span>
                    </td>
                    <td className={`${td} num`}>{l.tvCount}</td>
                    <td className={td}>
                      <StatusBadge status={l.status} />
                    </td>
                    <td className={`${td} text-muted`}>{formatDateTime(l.createdAt, ADMIN_TZ)}</td>
                  </tr>
                ))}
              </tbody>
            </TableWrap>
          </div>
        )}
      </Panel>
      {pages > 1 && (
        <nav aria-label="Pagination" className="flex items-center justify-between">
          {page > 1 ? (
            <ButtonLink href={filterHref(status, page - 1)} variant="secondary" size="sm">
              ← Newer
            </ButtonLink>
          ) : (
            <span />
          )}
          <span className="text-sm text-muted">
            Page {page} of {pages}
          </span>
          {page < pages ? (
            <ButtonLink href={filterHref(status, page + 1)} variant="secondary" size="sm">
              Older →
            </ButtonLink>
          ) : (
            <span />
          )}
        </nav>
      )}
    </div>
  );
}
