'use client';

/**
 * Platform admin acting as a venue host: the token is only minted (and audited) when the admin
 * explicitly takes control, then the shared live-control screen runs exactly as it does for hosts.
 */
import { useState, useTransition } from 'react';
import type { Standing } from '@pintrush/engine';
import { Button } from '@/components/ui/Button';
import { LiveControl, type LiveControlEvent } from '@/components/host/live/LiveControl';
import { Notice, Panel } from '@/components/host/ui';

export function AdminLiveControl({
  event,
  venueName,
  tvUrl,
  finalStandings,
  takeControl,
}: {
  event: LiveControlEvent;
  venueName: string;
  tvUrl: string;
  finalStandings: Standing[] | null;
  takeControl: () => Promise<{ ok: true; token: string } | { ok: false; message: string }>;
}) {
  const [token, setToken] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [pending, startTransition] = useTransition();

  if (token) {
    return (
      <div className="flex flex-col gap-4">
        <Notice tone="warning" title={`Acting as a host for ${venueName}`}>
          Every command you send is recorded in the session’s audit log under your admin account.
        </Notice>
        <LiveControl event={event} hostToken={token} tvUrl={tvUrl} finalStandings={finalStandings} />
      </div>
    );
  }
  return (
    <Panel title={event.name} description={`${event.kind === 'CHAMPIONSHIP' ? 'Championship' : 'Always-on night'} · ${event.roomName} · ${event.whenLabel}`}>
      <div className="flex flex-col items-start gap-4">
        <p className="max-w-2xl text-sm text-muted">
          Take control to open, start, pause, skip or end this event and to moderate nicknames on behalf of {venueName}. This issues a 12-hour host
          token for this venue and writes an audit entry.
        </p>
        <Button
          onClick={() =>
            startTransition(async () => {
              setError(null);
              const res = await takeControl();
              if (res.ok) setToken(res.token);
              else setError(res.message);
            })
          }
          disabled={pending}
          aria-busy={pending || undefined}
        >
          {pending ? 'Connecting…' : 'Take control as venue host'}
        </Button>
        <div role="alert">{error && <Notice tone="error">{error}</Notice>}</div>
      </div>
    </Panel>
  );
}
