import type { Metadata } from 'next';
import Link from 'next/link';
import { notFound } from 'next/navigation';
import { forVenue, getDb, parseEventConfig } from '@pintrush/db';
import { formatBusinessDate, formatDateTime } from '@/components/host/format';
import { LiveControl } from '@/components/host/live/LiveControl';
import { linkStyles } from '@/components/host/ui';
import { requireHost } from '@/lib/auth/session';
import { signHostToken, tvUrl } from '@/lib/server/tokens';
import { siteUrl } from '@/lib/site';
import { finalStandings } from '../../../_lib/data';

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

export default async function EventControlPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const { venue, user } = await requireHost(`/host/events/${encodeURIComponent(id)}`);
  const scope = forVenue(getDb(), venue.id);
  // Venue-scoped lookups: another venue's event or room is simply "not found".
  const event = await scope.events.get(id);
  if (!event) notFound();
  const room = await scope.rooms.get(event.roomId);
  if (!room) notFound();

  const [hostToken, tv, standings] = await Promise.all([
    signHostToken({ sub: user.id, venueId: venue.id, role: user.role }),
    tvUrl(siteUrl.origin, room),
    event.status === 'COMPLETED' ? finalStandings(venue.id, event.id) : Promise.resolve(null),
  ]);
  const planLength = event.kind === 'CHAMPIONSHIP' ? parseEventConfig(event.config).plan.length : null;
  const whenLabel =
    event.kind === 'ALWAYS_ON'
      ? event.businessDate
        ? formatBusinessDate(event.businessDate)
        : 'Tonight'
      : formatDateTime(event.scheduledAt, venue.timezone, 'full');

  return (
    <div className="flex flex-col gap-4">
      <nav aria-label="Breadcrumb" className="text-sm">
        <Link href="/host/events" className={linkStyles}>
          ← All events
        </Link>
      </nav>
      <LiveControl
        event={{ id: event.id, name: event.name, kind: event.kind, status: event.status, whenLabel, roomName: room.name, planLength }}
        hostToken={hostToken}
        tvUrl={tv}
        editHref={event.kind === 'CHAMPIONSHIP' && event.status === 'SCHEDULED' ? `/host/events/${event.id}/edit` : undefined}
        finalStandings={standings}
      />
    </div>
  );
}
