import type { Metadata } from 'next';
import Link from 'next/link';
import { forVenue, getDb } from '@pintrush/db';
import type { VenueEvent } from '@pintrush/db';
import { ButtonLink } from '@/components/ui/Button';
import { CalendarIcon } from '@/components/ui/icons';
import { formatBusinessDate, formatDateTime, formatNumber, formatRelative } from '@/components/host/format';
import { EmptyState, linkStyles, PageHeader, Panel, StatusBadge, TableWrap, td, th } from '@/components/host/ui';
import { requireHost } from '@/lib/auth/session';
import { eventPlayerCounts } from '../../_lib/data';

export const metadata: Metadata = { title: 'Events' };

function whenLabel(e: VenueEvent, timeZone: string): string {
  if (e.kind === 'ALWAYS_ON') return e.businessDate ? `${formatBusinessDate(e.businessDate)} (always-on night)` : 'Always-on night';
  return formatDateTime(e.scheduledAt, timeZone, 'full');
}

function EventTable({ events, timeZone, players, now }: { events: VenueEvent[]; timeZone: string; players: Map<string, number>; now: number }) {
  return (
    <TableWrap label="Events">
      <thead>
        <tr>
          <th scope="col" className={th}>
            Event
          </th>
          <th scope="col" className={th}>
            When
          </th>
          <th scope="col" className={th}>
            Room
          </th>
          <th scope="col" className={th}>
            Players
          </th>
          <th scope="col" className={th}>
            Status
          </th>
          <th scope="col" className={th}>
            <span className="sr-only">Actions</span>
          </th>
        </tr>
      </thead>
      <tbody>
        {events.map((e) => (
          <tr key={e.id}>
            <td className={td}>
              <span className="font-semibold">{e.name}</span>
              <span className="block text-xs text-subtle">{e.kind === 'CHAMPIONSHIP' ? 'Championship' : 'Always-on'}</span>
            </td>
            <td className={td}>
              {whenLabel(e, timeZone)}
              {e.kind === 'CHAMPIONSHIP' && e.status === 'SCHEDULED' && e.scheduledAt && (
                <span className="block text-xs text-subtle">{formatRelative(e.scheduledAt.getTime(), now)}</span>
              )}
            </td>
            <td className={td}>{e.room.name}</td>
            <td className={`${td} num`}>{formatNumber(players.get(e.id) ?? 0)}</td>
            <td className={td}>
              <StatusBadge status={e.status} />
            </td>
            <td className={`${td} text-right whitespace-nowrap`}>
              <span className="inline-flex gap-4">
                {e.kind === 'CHAMPIONSHIP' && e.status === 'SCHEDULED' && (
                  <Link href={`/host/events/${e.id}/edit`} className={linkStyles}>
                    Edit<span className="sr-only"> {e.name}</span>
                  </Link>
                )}
                <Link href={`/host/events/${e.id}`} className={linkStyles}>
                  {e.status === 'COMPLETED' || e.status === 'CANCELLED' ? 'Details' : 'Control'}
                  <span className="sr-only"> {e.name}</span>
                </Link>
              </span>
            </td>
          </tr>
        ))}
      </tbody>
    </TableWrap>
  );
}

export default async function EventsPage() {
  const { venue } = await requireHost('/host/events');
  const scope = forVenue(getDb(), venue.id);
  const now = Date.now();
  const [live, upcoming, past] = await Promise.all([
    scope.events.list({ status: ['LIVE', 'PAUSED'], order: 'asc', limit: 20 }),
    scope.events.list({ status: 'SCHEDULED', kind: 'CHAMPIONSHIP', order: 'asc', limit: 50 }),
    scope.events.list({ status: ['COMPLETED', 'CANCELLED'], order: 'desc', limit: 40 }),
  ]);
  // Past list: championships by show time; always-on nights have no scheduledAt, so sort by when they ended.
  const pastSorted = [...past].sort(
    (a, b) => (b.endedAt ?? b.scheduledAt ?? b.createdAt).getTime() - (a.endedAt ?? a.scheduledAt ?? a.createdAt).getTime(),
  );
  const players = await eventPlayerCounts(venue.id, [...live, ...upcoming, ...pastSorted].map((e) => e.id));

  return (
    <div className="flex flex-col gap-8">
      <PageHeader
        title="Events"
        description="Championships are hosted shows with their own leaderboard. Always-on nights run themselves during opening hours."
        actions={
          <ButtonLink href="/host/events/new">
            <CalendarIcon /> New championship
          </ButtonLink>
        }
      />
      <Panel title="Live now" padded={live.length === 0}>
        {live.length === 0 ? (
          <p className="text-sm text-muted">Nothing is live right now.</p>
        ) : (
          <div className="px-5 sm:px-6">
            <EventTable events={live} timeZone={venue.timezone} players={players} now={now} />
          </div>
        )}
      </Panel>
      <Panel title="Upcoming championships" padded={upcoming.length === 0}>
        {upcoming.length === 0 ? (
          <EmptyState title="No championships scheduled" action={<ButtonLink href="/host/events/new" size="sm">New championship</ButtonLink>} />
        ) : (
          <div className="px-5 sm:px-6">
            <EventTable events={upcoming} timeZone={venue.timezone} players={players} now={now} />
          </div>
        )}
      </Panel>
      <Panel title="Past events" description="The 40 most recent." padded={pastSorted.length === 0}>
        {pastSorted.length === 0 ? (
          <p className="text-sm text-muted">No past events yet.</p>
        ) : (
          <div className="px-5 sm:px-6">
            <EventTable events={pastSorted} timeZone={venue.timezone} players={players} now={now} />
          </div>
        )}
      </Panel>
    </div>
  );
}
