import Link from 'next/link';
import { notFound } from 'next/navigation';
import { ArrowLeft, Download, MonitorSmartphone } from 'lucide-react';
import { requireRole } from '@/lib/auth/dal';
import { getEventForUser, listParticipants } from '@/lib/events/queries';
import { setEventStatus } from '@/app/actions/events';
import type { AuraCalculationResult } from '@/lib/aura/types';
import { Button } from '@/components/ui/Button';
import { ShellPage } from '@/components/layout/DashboardPage';
import { StatusPill } from '@/components/admin/StatusPill';
import { ParticipantQrButton } from '@/components/admin/ParticipantQrButton';
import { getLocale, getMessages } from '@/i18n/server';
import { INTL_LOCALE } from '@/i18n/config';

export default async function EventPage({ params }: PageProps<'/admin/sesi/[id]'>) {
  const { id } = await params;
  const user = await requireRole(['ADMIN', 'SUPER_ADMIN'], `/admin/sesi/${id}`);
  const event = await getEventForUser(id, user);
  if (!event) notFound();
  const participants = await listParticipants(event.id);
  const isActive = event.status === 'AKTIF';
  const claimed = participants.filter((p) => p.ownerId).length;
  const all = (await getMessages()).admin;
  const t = all.event;
  const intl = INTL_LOCALE[await getLocale()];
  const dateFmt = new Intl.DateTimeFormat(intl, { day: 'numeric', month: 'long', year: 'numeric' });
  const timeFmt = new Intl.DateTimeFormat(intl, { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' });

  return (
    <ShellPage>
      <Link href="/admin/sesi" className="inline-flex items-center gap-1.5 text-[13px] font-medium text-muted hover:text-ink">
        <ArrowLeft className="size-4" aria-hidden />
        {t.back}
      </Link>

      <div className="mt-6 flex flex-col gap-6 lg:flex-row lg:items-end lg:justify-between">
        <div className="min-w-0">
          <div className="flex flex-wrap items-center gap-3">
            <h1 className="text-[28px] leading-tight font-semibold tracking-[-0.02em] text-ink">{event.name}</h1>
            <StatusPill status={event.status} label={all.status[event.status]} />
          </div>
          <p className="mt-2 text-[15px] text-muted">
            {[
              all.kinds[event.kind],
              event.location,
              event.date && dateFmt.format(event.date),
              t.createdBy(event.createdBy.name),
            ]
              .filter(Boolean)
              .join(' · ')}
          </p>
        </div>

        <div className="flex flex-wrap items-center gap-3">
          <form action={setEventStatus}>
            <input type="hidden" name="id" value={event.id} />
            <input type="hidden" name="status" value={isActive ? 'SELESAI' : 'AKTIF'} />
            <Button type="submit" variant="outline">
              {isActive ? t.close : t.reopen}
            </Button>
          </form>
          {participants.length > 0 && (
            // Plain anchor: a file download, not a client-side navigation.
            <a
              href={`/admin/sesi/${event.id}/ekspor`}
              className="inline-flex h-12 items-center gap-2 rounded-full border border-line-strong bg-white px-6 text-sm font-semibold text-ink transition-colors hover:border-ink/30"
            >
              <Download className="size-4" aria-hidden />
              {t.exportCsv}
            </a>
          )}
          {isActive && (
            <Button href={`/admin/sesi/${event.id}/kios`}>
              <MonitorSmartphone className="size-4" aria-hidden />
              {t.startKiosk}
            </Button>
          )}
        </div>
      </div>

      <dl className="mt-10 grid grid-cols-2 gap-px overflow-hidden rounded-card bg-line shadow-card ring-1 ring-line sm:max-w-md">
        {(
          [
            [t.participants, participants.length],
            [t.claimed, claimed],
          ] as const
        ).map(([label, value]) => (
          <div key={label} className="bg-surface p-5">
            <dt className="text-[13px] text-muted">{label}</dt>
            <dd className="mt-2 text-[28px] font-semibold tracking-tight text-ink tabular-nums">{value}</dd>
          </div>
        ))}
      </dl>

      <section aria-labelledby="participants" className="mt-12">
        <h2 id="participants" className="text-[15px] font-semibold text-ink">
          {t.participants}
        </h2>
        {participants.length === 0 ? (
          <div className="mt-4 rounded-panel bg-surface px-6 py-16 text-center shadow-card ring-1 ring-line/70">
            <p className="text-lg font-semibold text-ink">{t.emptyTitle}</p>
            <p className="mx-auto mt-2 max-w-sm text-sm leading-relaxed text-muted">
              {isActive ? t.emptyActive : t.emptyClosed}
            </p>
          </div>
        ) : (
          <div className="mt-4 overflow-x-auto rounded-card bg-surface shadow-card ring-1 ring-line/70">
            <table className="w-full min-w-[640px] text-left text-sm">
              <thead className="border-b border-line text-[12px] text-subtle">
                <tr>
                  <th scope="col" className="px-5 py-3 font-medium">
                    {t.cols.name}
                  </th>
                  <th scope="col" className="px-5 py-3 font-medium">
                    {t.cols.contact}
                  </th>
                  <th scope="col" className="px-5 py-3 font-medium">
                    {t.cols.profile}
                  </th>
                  <th scope="col" className="px-5 py-3 font-medium">
                    {t.cols.time}
                  </th>
                  <th scope="col" className="px-5 py-3 font-medium">
                    {t.cols.status}
                  </th>
                  <th scope="col" className="px-3 py-3">
                    <span className="sr-only">{t.cols.actions}</span>
                  </th>
                </tr>
              </thead>
              <tbody className="divide-y divide-line">
                {participants.map((p) => (
                  <tr key={p.id} className="transition-colors hover:bg-canvas/60">
                    <td className="px-5 py-3.5">
                      <Link href={`/laporan/${p.id}`} className="font-semibold text-ink hover:underline">
                        {p.subjectName}
                      </Link>
                    </td>
                    <td className="px-5 py-3.5 text-muted">{p.subjectEmail || p.subjectPhone || '—'}</td>
                    <td className="px-5 py-3.5 text-ink-soft">
                      {(p.aura as unknown as AuraCalculationResult | null)?.auraProfile ?? '—'}
                    </td>
                    <td className="px-5 py-3.5 text-muted tabular-nums">{timeFmt.format(p.createdAt)}</td>
                    <td className="px-5 py-3.5">
                      <span className={p.ownerId ? 'text-wood' : 'text-subtle'}>
                        {p.ownerId ? t.saved : t.notSaved}
                      </span>
                    </td>
                    <td className="px-3 py-2 text-right">
                      <ParticipantQrButton token={p.shareToken} name={p.subjectName} claimed={Boolean(p.ownerId)} />
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </section>
    </ShellPage>
  );
}
