import type { Metadata } from 'next';
import Link from 'next/link';
import { notFound } from 'next/navigation';
import { getDb, isUuid } from '@pintrush/db';
import { ButtonLink } from '@/components/ui/Button';
import { TvIcon } from '@/components/ui/icons';
import { AddRoomForm, AddUserForm, EntitlementForm, VenueStatusForm } from '@/components/admin/VenueForms';
import { ConfirmActionButton, CopyButton } from '@/components/host/client';
import { formatBusinessDate, formatDate, formatDateTime } from '@/components/host/format';
import { linkStyles, Notice, PageHeader, Panel, StatusBadge, TableWrap, td, th } from '@/components/host/ui';
import { requireAdmin } from '@/lib/auth/session';
import { tvUrl } from '@/lib/server/tokens';
import { siteUrl } from '@/lib/site';
import { ADMIN_TZ, ENTITLEMENT_STATUSES, VENUE_STATUSES } from '../../../_lib/constants';
import { addRoom, addVenueUser, adminResetTvLink, changeVenueUserRole, removeVenueUser, resetVenueUserPassword, saveEntitlement, setVenueStatus } from '../actions';

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

export default async function AdminVenuePage({
  params,
  searchParams,
}: {
  params: Promise<{ id: string }>;
  searchParams: Promise<Record<string, string | string[] | undefined>>;
}) {
  const { id } = await params;
  const removedParam = (await searchParams).userRemoved;
  const removedEmail = typeof removedParam === 'string' ? removedParam.slice(0, 254) : null;
  await requireAdmin(`/admin/venues/${encodeURIComponent(id)}`);
  if (!isUuid(id)) notFound();
  const db = getDb();
  const venue = await db.venue.findUnique({
    where: { id },
    include: {
      rooms: { orderBy: { createdAt: 'asc' } },
      users: { orderBy: { createdAt: 'asc' }, select: { id: true, name: true, email: true, role: true, lastLoginAt: true, createdAt: true } },
      entitlements: { orderBy: { createdAt: 'desc' }, include: { plan: { select: { key: true, name: true } } } },
    },
  });
  if (!venue) notFound();
  const [plans, events] = await Promise.all([
    db.plan.findMany({ orderBy: { sortOrder: 'asc' }, select: { key: true, name: true, priceCents: true, interval: true } }),
    db.event.findMany({
      where: { venueId: venue.id },
      orderBy: [{ createdAt: 'desc' }],
      take: 20,
      select: {
        id: true,
        name: true,
        kind: true,
        status: true,
        scheduledAt: true,
        businessDate: true,
        room: { select: { name: true } },
        gameSession: { select: { id: true, status: true, startedAt: true, _count: { select: { players: true } } } },
      },
    }),
  ]);
  const tvLinks = new Map(await Promise.all(venue.rooms.map(async (r) => [r.id, await tvUrl(siteUrl.origin, r)] as const)));
  const current = venue.entitlements[0] ?? null;
  const ownerCount = venue.users.filter((u) => u.role === 'OWNER').length;

  return (
    <div className="flex flex-col gap-8">
      <nav aria-label="Breadcrumb" className="text-sm">
        <Link href="/admin/venues" className={linkStyles}>
          ← All venues
        </Link>
      </nav>
      <PageHeader
        kicker={<>Venue · join code {venue.joinCode}</>}
        title={venue.name}
        description={
          <>
            <StatusBadge status={venue.status} /> <span className="ml-2">{venue.slug}</span> · {venue.timezone}
            {venue.address ? ` · ${venue.address}` : ''} · created {formatDate(venue.createdAt, ADMIN_TZ)}
          </>
        }
      />

      <Panel title="Status">
        <VenueStatusForm action={setVenueStatus} venueId={venue.id} status={venue.status} version={venue.version} statuses={VENUE_STATUSES} />
      </Panel>

      <Panel title="Rooms & TV links" padded={false}>
        <div className="px-5 sm:px-6">
          <TableWrap label="Rooms">
            <thead>
              <tr>
                <th scope="col" className={th}>
                  Room
                </th>
                <th scope="col" className={th}>
                  Status
                </th>
                <th scope="col" className={th}>
                  TV link
                </th>
                <th scope="col" className={th}>
                  <span className="sr-only">Actions</span>
                </th>
              </tr>
            </thead>
            <tbody>
              {venue.rooms.map((room) => (
                <tr key={room.id}>
                  <td className={td}>
                    <span className="font-semibold">{room.name}</span>
                    <span className="block text-xs text-subtle">{room.slug}</span>
                  </td>
                  <td className={`${td} text-muted`}>{room.status === 'ACTIVE' ? 'Active' : 'Archived'}</td>
                  <td className={td}>
                    <span className="flex flex-wrap gap-2">
                      <ButtonLink href={tvLinks.get(room.id) ?? '#'} target="_blank" rel="noopener noreferrer" prefetch={false} size="sm" variant="secondary">
                        <TvIcon /> Open<span className="sr-only"> TV screen for {room.name} (new tab)</span>
                      </ButtonLink>
                      <CopyButton value={tvLinks.get(room.id) ?? ''} label="Copy" />
                    </span>
                  </td>
                  <td className={`${td} text-right`}>
                    <div className="flex justify-end">
                      <ConfirmActionButton
                          align="end"
                        action={adminResetTvLink}
                        fields={{ venueId: venue.id, roomId: room.id }}
                        label="Reset TV link"
                        title={`Reset the TV link for ${room.name}?`}
                        description="Every TV using the current link is signed out the next time it reconnects. The venue needs the new link from its dashboard."
                        confirmLabel="Reset TV link"
                      />
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </TableWrap>
        </div>
        <div className="border-t border-line/70 p-5 sm:p-6">
          <AddRoomForm action={addRoom} venueId={venue.id} />
        </div>
      </Panel>

      <Panel
        title="Venue users"
        description="Owners can change settings and TV links; hosts run events. Changing a role, resetting a password or removing a user signs that user out everywhere."
        padded={false}
      >
        {removedEmail && (
          <div className="px-5 pt-5 sm:px-6" role="status">
            <Notice tone="success">{removedEmail} was removed. They are signed out everywhere and can no longer sign in.</Notice>
          </div>
        )}
        <div className="px-5 sm:px-6">
          <TableWrap label="Venue users">
            <thead>
              <tr>
                <th scope="col" className={th}>
                  User
                </th>
                <th scope="col" className={th}>
                  Role
                </th>
                <th scope="col" className={th}>
                  Last sign-in
                </th>
                <th scope="col" className={th}>
                  <span className="sr-only">Actions</span>
                </th>
              </tr>
            </thead>
            <tbody>
              {venue.users.map((u) => {
                // An open venue keeps at least one owner (the actions enforce it; this just explains it up front).
                const lastOwner = u.role === 'OWNER' && ownerCount <= 1 && venue.status !== 'CANCELLED';
                const toRole = u.role === 'OWNER' ? 'HOST' : 'OWNER';
                return (
                  <tr key={u.id}>
                    <td className={td}>
                      <span className="font-semibold">{u.name}</span>
                      <span className="block text-xs text-subtle">{u.email}</span>
                    </td>
                    <td className={`${td} text-muted`}>
                      {u.role === 'OWNER' ? 'Owner' : 'Host'}
                      {lastOwner && <span className="block text-xs text-subtle">Only owner</span>}
                    </td>
                    <td className={`${td} text-muted`}>{u.lastLoginAt ? formatDateTime(u.lastLoginAt, ADMIN_TZ) : 'Never'}</td>
                    <td className={`${td} text-right`}>
                      <div className="flex flex-wrap items-start justify-end gap-2">
                        <ConfirmActionButton
                          align="end"
                          action={changeVenueUserRole}
                          fields={{ venueId: venue.id, userId: u.id, role: toRole }}
                          label={toRole === 'OWNER' ? 'Make owner' : 'Make host'}
                          title={toRole === 'OWNER' ? `Make ${u.name} an owner?` : `Make ${u.name} a host?`}
                          description={
                            <>
                              {toRole === 'OWNER'
                                ? 'Owners can also change venue settings, TV links and staff.'
                                : 'Hosts can run events but can no longer change venue settings or TV links.'}{' '}
                              They are signed out on every device and see the new access when they sign in again.
                            </>
                          }
                          confirmLabel={toRole === 'OWNER' ? 'Make owner' : 'Make host'}
                          tone="primary"
                          disabled={lastOwner}
                        />
                        <ConfirmActionButton
                          align="end"
                          action={resetVenueUserPassword}
                          fields={{ venueId: venue.id, userId: u.id }}
                          label="Reset password"
                          title={`Reset the password for ${u.email}?`}
                          description="Their current password stops working immediately and they are signed out on every device. You’ll see a new temporary password once — share it privately."
                          confirmLabel="Reset password"
                          tone="primary"
                        />
                        <ConfirmActionButton
                          align="end"
                          action={removeVenueUser}
                          fields={{ venueId: venue.id, userId: u.id }}
                          label={<>Remove<span className="sr-only"> {u.name}</span></>}
                          title={`Remove ${u.name} from ${venue.name}?`}
                          description="They are signed out on every device and can no longer sign in. Events they created stay. To give them access again, add them as a new user."
                          confirmLabel="Remove user"
                          disabled={lastOwner}
                        />
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </TableWrap>
        </div>
        <div className="border-t border-line/70 p-5 sm:p-6">
          <AddUserForm action={addVenueUser} venueId={venue.id} />
        </div>
      </Panel>

      <Panel title="Plan & entitlement" description="Pilot pricing only — no billing is connected, so this records what the venue is entitled to.">
        <EntitlementForm
          action={saveEntitlement}
          venueId={venue.id}
          plans={plans}
          statuses={ENTITLEMENT_STATUSES}
          entitlement={
            current
              ? {
                  id: current.id,
                  version: current.version,
                  planKey: current.plan.key,
                  status: current.status,
                  trialEndsAt: current.trialEndsAt ? current.trialEndsAt.toISOString().slice(0, 10) : '',
                }
              : null
          }
        />
        {venue.entitlements.length > 1 && (
          <details className="mt-5 text-sm">
            <summary className="inline-flex min-h-11 items-center font-semibold text-violet-soft">Earlier entitlements ({venue.entitlements.length - 1})</summary>
            <ul className="mt-2 space-y-1 text-muted">
              {venue.entitlements.slice(1).map((e) => (
                <li key={e.id}>
                  {e.plan.name} · {e.status.toLowerCase()} · created {formatDate(e.createdAt, ADMIN_TZ)}
                </li>
              ))}
            </ul>
          </details>
        )}
      </Panel>

      <Panel title="Recent events & sessions" description="The 20 most recent events. Control opens the live host screen acting for this venue." padded={false}>
        {events.length === 0 ? (
          <p className="p-5 text-sm text-muted sm:p-6">No events yet.</p>
        ) : (
          <div className="px-5 sm:px-6">
            <TableWrap label="Recent events">
              <thead>
                <tr>
                  <th scope="col" className={th}>
                    Event
                  </th>
                  <th scope="col" className={th}>
                    When
                  </th>
                  <th scope="col" className={th}>
                    Status
                  </th>
                  <th scope="col" className={th}>
                    Players
                  </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'} · {e.room.name}
                      </span>
                    </td>
                    <td className={`${td} text-muted`}>
                      {e.kind === 'ALWAYS_ON' && e.businessDate ? formatBusinessDate(e.businessDate) : formatDateTime(e.scheduledAt, venue.timezone)}
                    </td>
                    <td className={td}>
                      <StatusBadge status={e.status} />
                    </td>
                    <td className={`${td} num text-muted`}>{e.gameSession?._count.players ?? 0}</td>
                    <td className={`${td} text-right whitespace-nowrap`}>
                      <span className="inline-flex gap-4">
                        {e.gameSession && (
                          <Link href={`/admin/support?session=${e.gameSession.id}`} className={linkStyles}>
                            Audit log<span className="sr-only"> for {e.name}</span>
                          </Link>
                        )}
                        <Link href={`/admin/venues/${venue.id}/events/${e.id}`} className={linkStyles}>
                          Control<span className="sr-only"> {e.name}</span>
                        </Link>
                      </span>
                    </td>
                  </tr>
                ))}
              </tbody>
            </TableWrap>
          </div>
        )}
      </Panel>
    </div>
  );
}
