import type { Metadata } from 'next';
import { addDaysToDate, defaultChampionshipPlan, forVenue, getDb, localDate, zonedDateTimeToEpoch } from '@pintrush/db';
import { EventForm } from '@/components/host/events/EventForm';
import { zoneAbbreviation } from '@/components/host/format';
import { EmptyState, PageHeader, Panel } from '@/components/host/ui';
import { requireHost } from '@/lib/auth/session';
import { visiblePacks } from '../../../_lib/data';
import { createChampionship } from '../actions';

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

/** Suggest the next Friday at 9 pm (venue time) that is still ahead — the classic championship slot. */
function suggestedSlot(timeZone: string, now: number): { date: string; time: string } {
  const today = localDate(timeZone, now);
  for (let delta = 0; delta <= 7; delta++) {
    const date = addDaysToDate(today, delta);
    if (new Date(`${date}T12:00:00Z`).getUTCDay() !== 5) continue;
    if (zonedDateTimeToEpoch(timeZone, date, '21:00') > now) return { date, time: '21:00' };
  }
  return { date: addDaysToDate(today, 7), time: '21:00' };
}

export default async function NewChampionshipPage() {
  const { venue } = await requireHost('/host/events/new');
  const scope = forVenue(getDb(), venue.id);
  const [rooms, packs, settings] = await Promise.all([scope.rooms.list(), visiblePacks(venue.id), scope.venue.settings()]);
  const activeRooms = rooms.filter((r) => r.status === 'ACTIVE').map((r) => ({ id: r.id, name: r.name }));
  const slot = suggestedSlot(venue.timezone, Date.now());
  const plan = defaultChampionshipPlan().map(({ kind, packKey, label }) => ({ kind, packKey, label }));

  return (
    <div className="flex flex-col gap-8">
      <PageHeader
        kicker="Events"
        title="New championship"
        description="A hosted show with its own leaderboard. Everyone starts at zero; the lobby opens automatically 15 minutes before the start, or whenever you open it."
      />
      <Panel>
        {activeRooms.length === 0 ? (
          <EmptyState title="Your venue has no rooms yet">Contact PintRush support to add one.</EmptyState>
        ) : (
          <EventForm
            mode="create"
            action={createChampionship}
            rooms={activeRooms}
            packs={packs}
            defaultPlan={plan}
            initial={{ name: '', roomId: activeRooms[0]!.id, date: slot.date, time: slot.time, plan, mergeSolos: settings?.mergeSolos ?? false }}
            timeZoneLabel={`Venue time (${zoneAbbreviation(venue.timezone)})`}
          />
        )}
      </Panel>
    </div>
  );
}
