import type { Metadata } from 'next';
import { DEFAULT_VENUE_SETTINGS, forVenue, getDb } from '@pintrush/db';
import { ConfirmActionButton } from '@/components/host/client';
import { SettingsForm } from '@/components/host/settings/SettingsForm';
import { Notice, PageHeader, Panel, TableWrap, td, th } from '@/components/host/ui';
import { isOwner, requireHost } from '@/lib/auth/session';
import { visiblePacks } from '../../_lib/data';
import { resetTvLink, saveVenueSettings } from './actions';

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

export default async function SettingsPage() {
  const ctx = await requireHost('/host/settings');
  const { venue } = ctx;
  const scope = forVenue(getDb(), venue.id);
  const [settings, packs, rooms] = await Promise.all([scope.venue.settings(), visiblePacks(venue.id), scope.rooms.list()]);
  const current = settings ?? DEFAULT_VENUE_SETTINGS;
  const owner = isOwner(ctx);

  return (
    <div className="flex flex-col gap-8">
      <PageHeader
        title="Settings"
        description={
          <>
            {venue.name} · times are in {venue.timezone.replace(/_/g, ' ')}.
          </>
        }
      />
      {!owner && (
        <Notice tone="info" title="View only">
          Only the venue owner can change settings and TV links. You can still run events and moderate players.
        </Notice>
      )}
      <Panel title="Always-on & teams">
        <SettingsForm
          action={saveVenueSettings}
          version={venue.version}
          canEdit={owner}
          packs={packs}
          initial={{
            enabled: current.alwaysOn.enabled,
            packKey: current.alwaysOn.packKey,
            mergeSolos: current.mergeSolos,
            schedule: current.alwaysOn.schedule,
          }}
        />
      </Panel>
      <Panel
        title="Rooms & TV links"
        description="Each room has one TV link. If a link leaks (say, someone photographed it), reset it: every TV using the old link is signed out and needs the new one."
        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 resets
                </th>
                <th scope="col" className={th}>
                  <span className="sr-only">Actions</span>
                </th>
              </tr>
            </thead>
            <tbody>
              {rooms.map((room) => (
                <tr key={room.id}>
                  <td className={`${td} font-semibold`}>{room.name}</td>
                  <td className={`${td} text-muted`}>{room.status === 'ACTIVE' ? 'Active' : 'Archived'}</td>
                  <td className={`${td} text-muted`}>
                    {room.tvTokenVersion > 1 ? `${room.tvTokenVersion - 1} time${room.tvTokenVersion === 2 ? '' : 's'}` : 'Never reset'}
                  </td>
                  <td className={`${td} text-right`}>
                    {owner && room.status === 'ACTIVE' && (
                      <div className="flex justify-end">
                        <ConfirmActionButton
                          align="end"
                          action={resetTvLink}
                          fields={{ roomId: room.id }}
                          label="Reset TV link"
                          title={`Reset the TV link for ${room.name}?`}
                          description="Every TV showing this room with the current link is signed out the next time it reconnects. You’ll need to open the new link (from the dashboard) on each TV."
                          confirmLabel="Reset TV link"
                        />
                      </div>
                    )}
                  </td>
                </tr>
              ))}
            </tbody>
          </TableWrap>
        </div>
      </Panel>
    </div>
  );
}
