import { TvApp } from '@/components/tv/TvApp';
import { TvAutoReload } from '@/components/tv/TvAutoReload';
import { TvMessageScreen } from '@/components/tv/TvMessageScreen';
import { TvStage } from '@/components/tv/TvStage';
import { QrCode } from '@/components/ui/QrCode';
import { joinUrl } from '@/lib/server/tokens';
import { siteUrl } from '@/lib/site';
import { displayJoinUrl, safeTimeZone } from '@/lib/tv/format';
import { loadTvRoom } from '@/lib/tv/room';
import { firstParam } from '@/lib/tv/token';

const LINK_HELP = 'Open the TV link from the PintRush host dashboard on this screen.';

const FAILURES = {
  missing: { title: 'This screen needs its TV link', body: `The address is missing its display key. ${LINK_HELP}` },
  invalid: { title: 'This TV link isn’t valid', body: `The link may be incomplete or copied wrong. ${LINK_HELP}` },
  revoked: { title: 'This TV link was reset', body: `A host replaced this room’s TV link, or the room was closed. ${LINK_HELP}` },
} as const;

/**
 * /tv/[roomId]?t=<tvToken> — the read-only bar TV. The server verifies the TV token, loads the room
 * and venue from the database (the URL's room id must match the token; nothing else in the URL is
 * trusted), renders the join QR code here so the QR library never ships to the browser, then hands
 * the live display to the client.
 */
export default async function TvPage({
  params,
  searchParams,
}: {
  params: Promise<{ roomId: string }>;
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const [{ roomId }, query] = await Promise.all([params, searchParams]);
  const token = firstParam(query.t);
  const result = await loadTvRoom(roomId, token);

  if (!result.ok) {
    if (result.reason === 'unavailable') {
      return (
        <TvStage label="PintRush TV display">
          <TvMessageScreen title="The game is taking a moment" body="This screen couldn’t load its room just now. It will try again by itself.">
            <TvAutoReload seconds={20} />
          </TvMessageScreen>
        </TvStage>
      );
    }
    const failure = FAILURES[result.reason];
    return (
      <TvStage label="PintRush TV display">
        <TvMessageScreen tone="error" title={failure.title} body={failure.body} />
      </TvStage>
    );
  }

  const { room } = result;
  const site = siteUrl.toString();
  const link = joinUrl(site, room.joinCode, room.roomId);
  return (
    <TvApp
      roomId={room.roomId}
      tvToken={token ?? ''}
      joinCode={room.joinCode}
      joinUrlText={displayJoinUrl(site, room.joinCode)}
      venueName={room.venueName}
      timeZone={safeTimeZone(room.timeZone)}
      qr={<QrCode value={link} label={`QR code to join PintRush at ${room.venueName}`} className="size-full" />}
    />
  );
}
