import type { Metadata } from 'next';
import type { ReactNode } from 'react';
import Link from 'next/link';
import { notFound } from 'next/navigation';
import { getDb, isUuid } from '@pintrush/db';
import { StatusSelectForm } from '@/components/admin/VenueForms';
import { ConfirmActionButton } from '@/components/host/client';
import { formatDateTime } from '@/components/host/format';
import { linkStyles, PageHeader, Panel, StatusBadge } from '@/components/host/ui';
import { requireAdmin } from '@/lib/auth/session';
import { NIGHT_LABELS, NIGHTS } from '@/lib/pilot';
import { ADMIN_TZ, LEAD_STATUSES } from '../../../_lib/constants';
import { deleteLead, setLeadStatus } from '../actions';

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

export default async function AdminLeadPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  await requireAdmin(`/admin/leads/${encodeURIComponent(id)}`);
  if (!isUuid(id)) notFound();
  const lead = await getDb().pilotLead.findUnique({ where: { id } });
  if (!lead) notFound();
  const nights = lead.busiestNights.map((n) => ((NIGHTS as readonly string[]).includes(n) ? NIGHT_LABELS[n as (typeof NIGHTS)[number]] : n));
  const rows: [string, ReactNode][] = [
    ['Address', lead.address],
    ['Contact', lead.contactName],
    [
      'Email',
      <a key="e" href={`mailto:${lead.email}`} className={linkStyles}>
        {lead.email}
      </a>,
    ],
    ['Phone', lead.phone ?? '—'],
    ['TVs', String(lead.tvCount)],
    ['Busiest nights', nights.length ? nights.join(', ') : '—'],
    ['Current entertainment', lead.currentEntertainment ?? '—'],
  ];

  return (
    <div className="flex flex-col gap-8">
      <nav aria-label="Breadcrumb" className="text-sm">
        <Link href="/admin/leads" className={linkStyles}>
          ← All leads
        </Link>
      </nav>
      <PageHeader
        kicker="Pilot lead"
        title={lead.venueName}
        description={
          <>
            <StatusBadge status={lead.status} /> <span className="ml-2">Received {formatDateTime(lead.createdAt, ADMIN_TZ, 'full')}</span>
          </>
        }
      />
      <div className="grid gap-8 lg:grid-cols-[1.4fr_1fr]">
        <Panel title="Application">
          <dl className="grid gap-x-6 gap-y-4 sm:grid-cols-[12rem_1fr]">
            {rows.map(([label, value]) => (
              <div key={label} className="contents">
                <dt className="text-sm text-subtle">{label}</dt>
                <dd className="text-fg">{value}</dd>
              </div>
            ))}
          </dl>
          {lead.message && (
            <div className="mt-6 border-t border-line/70 pt-5">
              <h3 className="text-sm font-semibold text-subtle">Message</h3>
              <p className="mt-2 whitespace-pre-line">{lead.message}</p>
            </div>
          )}
        </Panel>
        <div className="flex flex-col gap-8">
          <Panel title="Status">
            <StatusSelectForm
              action={setLeadStatus}
              hidden={{ leadId: lead.id, expectedVersion: lead.version }}
              label="Lead status"
              value={lead.status}
              options={LEAD_STATUSES.map((s) => ({ value: s, label: s.charAt(0) + s.slice(1).toLowerCase() }))}
              submitLabel="Update status"
            />
            {lead.status === 'QUALIFIED' && (
              <p className="mt-4 text-sm text-muted">
                Ready to onboard?{' '}
                <Link href="/admin/venues/new" className={linkStyles}>
                  Create the venue
                </Link>
                , then mark this lead converted.
              </p>
            )}
          </Panel>
          <Panel title="Delete lead" description="Removes the application and its contact details for good. Use for spam or on request.">
            <ConfirmActionButton
              action={deleteLead}
              fields={{ leadId: lead.id }}
              label="Delete lead"
              variant="danger"
              title={`Delete the application from ${lead.venueName}?`}
              description="This permanently removes the lead and its contact details. It can’t be undone."
              confirmLabel="Delete permanently"
              requireText={lead.venueName}
            />
          </Panel>
        </div>
      </div>
    </div>
  );
}
