import type { Metadata } from 'next';
import Link from 'next/link';
import { getDb } from '@pintrush/db';
import { ButtonLink } from '@/components/ui/Button';
import { formatDate } from '@/components/host/format';
import { EmptyState, linkStyles, PageHeader, Panel, StatusBadge, TableWrap, td, th } from '@/components/host/ui';
import { requireAdmin } from '@/lib/auth/session';
import { ADMIN_TZ } from '../../_lib/constants';

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

export default async function AdminVenuesPage() {
  await requireAdmin('/admin/venues');
  const venues = await getDb().venue.findMany({
    orderBy: [{ createdAt: 'desc' }],
    select: {
      id: true,
      name: true,
      slug: true,
      joinCode: true,
      status: true,
      timezone: true,
      createdAt: true,
      _count: { select: { rooms: true, users: true } },
      entitlements: { orderBy: { createdAt: 'desc' }, take: 1, select: { status: true, trialEndsAt: true, plan: { select: { name: true } } } },
    },
  });

  return (
    <div className="flex flex-col gap-8">
      <PageHeader title="Venues" description={`${venues.length} venue${venues.length === 1 ? '' : 's'} on the platform.`} actions={<ButtonLink href="/admin/venues/new">New venue</ButtonLink>} />
      <Panel padded={venues.length === 0}>
        {venues.length === 0 ? (
          <EmptyState title="No venues yet" action={<ButtonLink href="/admin/venues/new" size="sm">Create the first venue</ButtonLink>} />
        ) : (
          <div className="px-5 sm:px-6">
            <TableWrap label="Venues">
              <thead>
                <tr>
                  <th scope="col" className={th}>
                    Venue
                  </th>
                  <th scope="col" className={th}>
                    Join code
                  </th>
                  <th scope="col" className={th}>
                    Status
                  </th>
                  <th scope="col" className={th}>
                    Plan
                  </th>
                  <th scope="col" className={th}>
                    Rooms / users
                  </th>
                  <th scope="col" className={th}>
                    Created
                  </th>
                </tr>
              </thead>
              <tbody>
                {venues.map((v) => {
                  const ent = v.entitlements[0];
                  return (
                    <tr key={v.id}>
                      <td className={td}>
                        <Link href={`/admin/venues/${v.id}`} className={linkStyles}>
                          {v.name}
                        </Link>
                        <span className="block text-xs text-subtle">
                          {v.slug} · {v.timezone}
                        </span>
                      </td>
                      <td className={`${td} num font-semibold text-amber-soft`}>{v.joinCode}</td>
                      <td className={td}>
                        <StatusBadge status={v.status} />
                      </td>
                      <td className={td}>
                        {ent ? (
                          <>
                            {ent.plan.name} <StatusBadge status={ent.status} />
                            {ent.status === 'TRIALING' && ent.trialEndsAt && <span className="block text-xs text-subtle">until {formatDate(ent.trialEndsAt, ADMIN_TZ)}</span>}
                          </>
                        ) : (
                          <span className="text-muted">No plan</span>
                        )}
                      </td>
                      <td className={`${td} num text-muted`}>
                        {v._count.rooms} / {v._count.users}
                      </td>
                      <td className={`${td} text-muted`}>{formatDate(v.createdAt, ADMIN_TZ)}</td>
                    </tr>
                  );
                })}
              </tbody>
            </TableWrap>
          </div>
        )}
      </Panel>
    </div>
  );
}
