import type { Metadata } from 'next';
import Link from 'next/link';
import { notFound } from 'next/navigation';
import { forVenue, getDb, isUuid, parseEventConfig } from '@pintrush/db';
import { AdminLiveControl } from '@/components/admin/AdminLiveControl';
import { formatBusinessDate, formatDateTime } from '@/components/host/format';
import { linkStyles } from '@/components/host/ui';
import { requireAdmin } from '@/lib/auth/session';
import { tvUrl } from '@/lib/server/tokens';
import { siteUrl } from '@/lib/site';
import { finalStandings } from '@/app/host/_lib/data';
import { issueAdminHostToken } from '../../../actions';

export const metadata: Metadata = { title: 'Event control' };

export default async function AdminEventControlPage({ params }: { params: Promise<{ id: string; eventId: string }> }) {
  const { id, eventId } = await params;
  await requireAdmin(`/admin/venues/${encodeURIComponent(id)}/events/${encodeURIComponent(eventId)}`);
  if (!isUuid(id)) notFound();
  const db = getDb();
  const venue = await db.venue.findUnique({ where: { id }, select: { id: true, name: true, timezone: true } });
  if (!venue) notFound();
  // Same venue-scoped lookups hosts use: an event of another venue is "not found" here too.
  const scope = forVenue(db, venue.id);
  const event = await scope.events.get(eventId);
  if (!event) notFound();
  const room = await scope.rooms.get(event.roomId);
  if (!room) notFound();

  const [tv, standings] = await Promise.all([
    tvUrl(siteUrl.origin, room),
    event.status === 'COMPLETED' ? finalStandings(venue.id, event.id) : Promise.resolve(null),
  ]);
  const whenLabel =
    event.kind === 'ALWAYS_ON' ? (event.businessDate ? formatBusinessDate(event.businessDate) : 'Tonight') : formatDateTime(event.scheduledAt, venue.timezone, 'full');
  const takeControl = issueAdminHostToken.bind(null, venue.id, event.id);

  return (
    <div className="flex flex-col gap-4">
      <nav aria-label="Breadcrumb" className="text-sm">
        <Link href={`/admin/venues/${venue.id}`} className={linkStyles}>
          ← {venue.name}
        </Link>
      </nav>
      <AdminLiveControl
        event={{
          id: event.id,
          name: event.name,
          kind: event.kind,
          status: event.status,
          whenLabel,
          roomName: room.name,
          planLength: event.kind === 'CHAMPIONSHIP' ? parseEventConfig(event.config).plan.length : null,
        }}
        venueName={venue.name}
        tvUrl={tv}
        finalStandings={standings}
        takeControl={takeControl}
      />
    </div>
  );
}
