import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { defaultChampionshipPlan, forVenue, getDb, localDate, parseEventConfig, zonedParts } from '@pintrush/db';
import { ButtonLink } from '@/components/ui/Button';
import { ConfirmActionButton } from '@/components/host/client';
import { EventForm } from '@/components/host/events/EventForm';
import { formatDateTime, zoneAbbreviation } from '@/components/host/format';
import { Notice, PageHeader, Panel } from '@/components/host/ui';
import { requireHost } from '@/lib/auth/session';
import { visiblePacks } from '../../../../_lib/data';
import { cancelChampionship, updateChampionship } from '../../actions';

export const metadata: Metadata = { title: 'Edit championship' };

export default async function EditChampionshipPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const { venue } = await requireHost(`/host/events/${encodeURIComponent(id)}/edit`);
  const scope = forVenue(getDb(), venue.id);
  // forVenue returns null for another venue's event: indistinguishable from "does not exist".
  const event = await scope.events.get(id);
  if (!event || event.kind !== 'CHAMPIONSHIP') notFound();

  if (event.status !== 'SCHEDULED') {
    return (
      <div className="flex flex-col gap-6">
        <PageHeader kicker="Events" title={event.name} />
        <Notice tone="info" title="This show can’t be edited any more">
          Details can only change while a championship is still scheduled. It is now {event.status.toLowerCase()}.
        </Notice>
        <div>
          <ButtonLink href={`/host/events/${event.id}`}>Go to the control page</ButtonLink>
        </div>
      </div>
    );
  }

  const [rooms, packs] = await Promise.all([scope.rooms.list(), visiblePacks(venue.id)]);
  const config = parseEventConfig(event.config);
  const at = event.scheduledAt?.getTime() ?? Date.now();
  const p = zonedParts(venue.timezone, at);
  const time = `${String(p.hour).padStart(2, '0')}:${String(p.minute).padStart(2, '0')}`;
  const plan = config.plan.map(({ kind, packKey, label }) => ({ kind, packKey, label }));
  const defaultPlan = defaultChampionshipPlan().map(({ kind, packKey, label }) => ({ kind, packKey, label }));

  return (
    <div className="flex flex-col gap-8">
      <PageHeader
        kicker="Edit championship"
        title={event.name}
        description={`Scheduled for ${formatDateTime(event.scheduledAt, venue.timezone, 'full')} in ${event.room.name}.`}
        actions={
          <ButtonLink href={`/host/events/${event.id}`} variant="secondary">
            Control page
          </ButtonLink>
        }
      />
      <Panel>
        <EventForm
          mode="edit"
          action={updateChampionship}
          rooms={rooms.map((r) => ({ id: r.id, name: r.name }))}
          packs={packs}
          defaultPlan={defaultPlan}
          initial={{ name: event.name, roomId: event.roomId, date: localDate(venue.timezone, at), time, plan, mergeSolos: config.mergeSolos }}
          timeZoneLabel={`Venue time (${zoneAbbreviation(venue.timezone)})`}
          eventId={event.id}
          version={event.version}
        />
      </Panel>
      <Panel title="Cancel this show" description="Guests who planned to come won’t see it on the TV any more. This can’t be undone.">
        <ConfirmActionButton
          action={cancelChampionship}
          fields={{ eventId: event.id, expectedVersion: event.version }}
          label="Cancel championship"
          variant="danger"
          title={`Cancel “${event.name}”?`}
          description="The show is removed from the TV’s “next championship” slot and can’t be opened any more."
          confirmLabel="Yes, cancel the show"
        />
      </Panel>
    </div>
  );
}
