import type { Metadata } from 'next';
import Link from 'next/link';
import { getDb } from '@pintrush/db';
import { CheckIcon } from '@/components/ui/icons';
import { formatDate, formatPrice } from '@/components/host/format';
import { linkStyles, Notice, PageHeader, Panel, StatusBadge, TableWrap, td, th } from '@/components/host/ui';
import { requireAdmin } from '@/lib/auth/session';
import { ADMIN_TZ } from '../../_lib/constants';

export const metadata: Metadata = { title: 'Plans' };

export default async function AdminPlansPage() {
  await requireAdmin('/admin/plans');
  const db = getDb();
  const [plans, entitlements] = await Promise.all([
    db.plan.findMany({ orderBy: { sortOrder: 'asc' }, include: { _count: { select: { entitlements: true } } } }),
    db.entitlement.findMany({
      orderBy: [{ updatedAt: 'desc' }],
      include: { plan: { select: { name: true } }, venue: { select: { id: true, name: true, status: true } } },
      take: 200,
    }),
  ]);

  return (
    <div className="flex flex-col gap-8">
      <PageHeader title="Plans & entitlements" description="Pilot pricing hypotheses (spec §9). Prices come from the seed and are display-only." />
      <Notice tone="info" title="Billing is not connected">
        No payment provider is configured. Entitlements record what each venue is entitled to; change them from the venue’s page.
      </Notice>
      <div className="grid gap-4 md:grid-cols-3">
        {plans.map((p) => (
          <section key={p.id} aria-labelledby={`plan-${p.key}`} className="rounded-card border border-line bg-surface/85 p-6 shadow-card">
            <h2 id={`plan-${p.key}`} className="font-display text-xl font-bold">
              {p.name}
            </h2>
            <p className="num mt-2 font-display text-3xl font-bold text-gradient-brand">{formatPrice(p.priceCents, p.interval)}</p>
            <p className="mt-1 text-xs text-subtle">
              key <code>{p.key}</code> · {p.isPublic ? 'public' : 'hidden'} · {p._count.entitlements} entitlement{p._count.entitlements === 1 ? '' : 's'}
            </p>
            <ul className="mt-4 space-y-2 text-sm text-muted">
              {p.features.map((f) => (
                <li key={f} className="flex gap-2">
                  <CheckIcon className="mt-0.5 size-4 shrink-0 text-lime" />
                  {f}
                </li>
              ))}
            </ul>
          </section>
        ))}
      </div>
      <Panel title="Entitlements by venue" padded={entitlements.length === 0}>
        {entitlements.length === 0 ? (
          <p className="text-sm text-muted">No entitlements yet.</p>
        ) : (
          <div className="px-5 sm:px-6">
            <TableWrap label="Entitlements">
              <thead>
                <tr>
                  <th scope="col" className={th}>
                    Venue
                  </th>
                  <th scope="col" className={th}>
                    Plan
                  </th>
                  <th scope="col" className={th}>
                    Status
                  </th>
                  <th scope="col" className={th}>
                    Trial ends
                  </th>
                  <th scope="col" className={th}>
                    Period ends
                  </th>
                </tr>
              </thead>
              <tbody>
                {entitlements.map((e) => (
                  <tr key={e.id}>
                    <td className={td}>
                      <Link href={`/admin/venues/${e.venue.id}`} className={linkStyles}>
                        {e.venue.name}
                      </Link>
                      {e.venue.status === 'CANCELLED' && <span className="ml-2 text-xs text-subtle">(venue cancelled)</span>}
                    </td>
                    <td className={td}>{e.plan.name}</td>
                    <td className={td}>
                      <StatusBadge status={e.status} />
                    </td>
                    <td className={`${td} text-muted`}>{formatDate(e.trialEndsAt, ADMIN_TZ)}</td>
                    <td className={`${td} text-muted`}>{formatDate(e.currentPeriodEnd, ADMIN_TZ)}</td>
                  </tr>
                ))}
              </tbody>
            </TableWrap>
          </div>
        )}
      </Panel>
    </div>
  );
}
