import type { Metadata } from 'next';
import Link from 'next/link';
import { getDb } from '@pintrush/db';
import { formatDateTime, formatNumber } from '@/components/host/format';
import { linkStyles, PageHeader, Panel, StatCard, StatusBadge } from '@/components/host/ui';
import { requireAdmin } from '@/lib/auth/session';
import { ADMIN_TZ } from '../_lib/constants';

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

const DAY_MS = 86_400_000;

export default async function AdminOverviewPage() {
  await requireAdmin('/admin');
  const db = getDb();
  const since = new Date(Date.now() - 7 * DAY_MS);
  const [venuesByStatus, rooms, users, liveSessions, newLeads, packs, questions, joins7d, rounds7d, recentLeads] = await Promise.all([
    db.venue.groupBy({ by: ['status'], _count: { _all: true } }),
    db.room.count({ where: { status: 'ACTIVE' } }),
    db.venueUser.count(),
    db.gameSession.findMany({
      where: { status: { in: ['WAITING', 'RUNNING', 'PAUSED'] } },
      select: { id: true, status: true, venueId: true, event: { select: { id: true, name: true, kind: true } }, room: { select: { name: true, venue: { select: { name: true } } } } },
      orderBy: { createdAt: 'desc' },
      take: 20,
    }),
    db.pilotLead.count({ where: { status: 'NEW' } }),
    db.questionPack.count({ where: { status: 'PUBLISHED' } }),
    db.question.count({ where: { status: 'ACTIVE' } }),
    db.playerSession.count({ where: { joinedAt: { gte: since } } }),
    db.round.count({ where: { status: 'COMPLETED', completedAt: { gte: since } } }),
    db.pilotLead.findMany({ orderBy: { createdAt: 'desc' }, take: 5, select: { id: true, venueName: true, contactName: true, status: true, createdAt: true } }),
  ]);
  const venueCount = (s: string) => venuesByStatus.find((v) => v.status === s)?._count._all ?? 0;
  const totalVenues = venuesByStatus.reduce((n, v) => n + v._count._all, 0);

  return (
    <div className="flex flex-col gap-8">
      <PageHeader title="Platform overview" description="Everything across all venues. Times in Eastern time." />
      <dl className="grid grid-cols-2 gap-3 md:grid-cols-4">
        <StatCard label="Venues" value={formatNumber(totalVenues)} hint={`${venueCount('PILOT')} pilot · ${venueCount('ACTIVE')} active · ${venueCount('PAUSED')} paused · ${venueCount('CANCELLED')} cancelled`} tone="violet" />
        <StatCard label="Active rooms" value={formatNumber(rooms)} hint={`${formatNumber(users)} venue users`} tone="cyan" />
        <StatCard label="Joins (7 days)" value={formatNumber(joins7d)} hint={`${formatNumber(rounds7d)} rounds completed`} tone="lime" />
        <StatCard label="New pilot leads" value={formatNumber(newLeads)} hint={`${formatNumber(packs)} published packs · ${formatNumber(questions)} questions`} tone="amber" />
      </dl>
      <div className="grid gap-8 lg:grid-cols-2">
        <Panel title="Live sessions" description="Game sessions that are open, running or paused right now.">
          {liveSessions.length === 0 ? (
            <p className="text-sm text-muted">Nothing is live.</p>
          ) : (
            <ul className="divide-y divide-line/60">
              {liveSessions.map((s) => (
                <li key={s.id} className="flex flex-wrap items-center justify-between gap-3 py-3 first:pt-0 last:pb-0">
                  <div className="min-w-0">
                    <p className="font-semibold">{s.event.name}</p>
                    <p className="text-sm text-muted">
                      {s.room.venue.name} · {s.room.name} · {s.event.kind === 'CHAMPIONSHIP' ? 'Championship' : 'Always-on'}
                    </p>
                  </div>
                  <span className="flex items-center gap-3">
                    <StatusBadge status={s.status} />
                    <Link href={`/admin/venues/${s.venueId}/events/${s.event.id}`} className={linkStyles}>
                      Control
                    </Link>
                  </span>
                </li>
              ))}
            </ul>
          )}
        </Panel>
        <Panel
          title="Latest pilot leads"
          actions={
            <Link href="/admin/leads" className={`${linkStyles} text-sm`}>
              All leads
            </Link>
          }
        >
          {recentLeads.length === 0 ? (
            <p className="text-sm text-muted">No applications yet.</p>
          ) : (
            <ul className="divide-y divide-line/60">
              {recentLeads.map((l) => (
                <li key={l.id} className="flex flex-wrap items-center justify-between gap-3 py-3 first:pt-0 last:pb-0">
                  <div className="min-w-0">
                    <Link href={`/admin/leads/${l.id}`} className={linkStyles}>
                      {l.venueName}
                    </Link>
                    <p className="text-sm text-muted">
                      {l.contactName} · {formatDateTime(l.createdAt, ADMIN_TZ)}
                    </p>
                  </div>
                  <StatusBadge status={l.status} />
                </li>
              ))}
            </ul>
          )}
        </Panel>
      </div>
    </div>
  );
}
