import type { Metadata } from 'next';
import Link from 'next/link';
import { getDb } from '@pintrush/db';
import { ConfirmActionButton } from '@/components/host/client';
import { formatNumber } from '@/components/host/format';
import { linkStyles, PageHeader, Panel, StatusBadge, TableWrap, td, th } from '@/components/host/ui';
import { requireAdmin } from '@/lib/auth/session';
import { setPackStatus } from './actions';

export const metadata: Metadata = { title: 'Question packs' };

function categoriesOf(json: unknown): { key: string; label: string }[] {
  return Array.isArray(json)
    ? json.flatMap((c) => (c && typeof c === 'object' && typeof (c as { key?: unknown }).key === 'string' ? [{ key: (c as { key: string }).key, label: String((c as { label?: unknown }).label ?? (c as { key: string }).key) }] : []))
    : [];
}

export default async function AdminPacksPage() {
  await requireAdmin('/admin/packs');
  const db = getDb();
  const [packs, counts] = await Promise.all([
    db.questionPack.findMany({ orderBy: [{ status: 'asc' }, { name: 'asc' }], include: { venue: { select: { name: true } } } }),
    db.question.groupBy({ by: ['packId', 'category', 'difficulty'], where: { status: 'ACTIVE' }, _count: { _all: true } }),
  ]);

  return (
    <div className="flex flex-col gap-8">
      <PageHeader title="Question packs" description="Original content only — no recordings, no lyrics. Counts are active questions." />
      {packs.map((pack) => {
        const mine = counts.filter((c) => c.packId === pack.id);
        const total = mine.reduce((n, c) => n + c._count._all, 0);
        const cats = categoriesOf(pack.categories);
        const extra = [...new Set(mine.map((c) => c.category))].filter((k) => !cats.some((c) => c.key === k)).map((key) => ({ key, label: key }));
        const count = (category: string, difficulty: 'STANDARD' | 'DIFFICULT') =>
          mine.find((c) => c.category === category && c.difficulty === difficulty)?._count._all ?? 0;
        const publish = pack.status !== 'PUBLISHED';
        return (
          <Panel
            key={pack.id}
            title={
              <span className="flex flex-wrap items-center gap-3">
                {pack.name} <StatusBadge status={pack.status} />
              </span>
            }
            description={`${pack.key} · ${pack.kind === 'MUSIC' ? 'Music' : 'General'} · ${pack.venue ? `private to ${pack.venue.name}` : 'platform pack'} · ${formatNumber(total)} questions`}
            actions={
              <>
                <Link href={`/admin/packs/${pack.id}`} className={`${linkStyles} text-sm`}>
                  Browse questions
                </Link>
                <ConfirmActionButton
                  action={setPackStatus}
                  fields={{ packId: pack.id, status: publish ? 'PUBLISHED' : 'ARCHIVED', expectedVersion: pack.version }}
                  label={publish ? 'Publish' : 'Archive'}
                  tone={publish ? 'primary' : 'danger'}
                  title={publish ? `Publish “${pack.name}”?` : `Archive “${pack.name}”?`}
                  description={
                    publish
                      ? 'Venues will be able to pick this pack for always-on and championship rounds.'
                      : 'Venues can no longer pick it. Always-on settings and scheduled shows that use it should be switched to another pack.'
                  }
                  confirmLabel={publish ? 'Publish pack' : 'Archive pack'}
                />
              </>
            }
            padded={false}
          >
            <div className="px-5 sm:px-6">
              <TableWrap label={`${pack.name} question counts`}>
                <thead>
                  <tr>
                    <th scope="col" className={th}>
                      Category
                    </th>
                    <th scope="col" className={`${th} text-right`}>
                      Standard
                    </th>
                    <th scope="col" className={`${th} text-right`}>
                      Difficult
                    </th>
                    <th scope="col" className={`${th} text-right`}>
                      Total
                    </th>
                  </tr>
                </thead>
                <tbody>
                  {[...cats, ...extra].map((c) => {
                    const s = count(c.key, 'STANDARD');
                    const d = count(c.key, 'DIFFICULT');
                    return (
                      <tr key={c.key}>
                        <td className={td}>
                          <Link href={`/admin/packs/${pack.id}?category=${encodeURIComponent(c.key)}`} className={linkStyles}>
                            {c.label}
                          </Link>
                          {!cats.some((x) => x.key === c.key) && <span className="ml-2 text-xs text-amber-soft">not a board category</span>}
                        </td>
                        <td className={`${td} num text-right`}>{s}</td>
                        <td className={`${td} num text-right`}>{d}</td>
                        <td className={`${td} num text-right font-semibold ${s + d < 10 ? 'text-amber-soft' : ''}`}>{s + d}</td>
                      </tr>
                    );
                  })}
                </tbody>
              </TableWrap>
            </div>
          </Panel>
        );
      })}
    </div>
  );
}
