import type { Metadata } from 'next';
import { notFound, redirect } from 'next/navigation';
import { getCurrentUser } from '@/lib/auth/dal';
import { canViewReport, findReportByToken, toReportData } from '@/lib/reports/access';
import { ReportView } from '@/components/report/ReportView';
import { Button } from '@/components/ui/Button';
import { Logo } from '@/components/ui/Logo';
import { getMessages } from '@/i18n/server';

export async function generateMetadata(): Promise<Metadata> {
  return { title: (await getMessages()).account.sharedMeta, robots: { index: false, follow: false } };
}

/** A participant's report, opened from the QR code shown at a session. */
export default async function SharedReportPage({ params }: PageProps<'/r/[token]'>) {
  const { token } = await params;
  const row = await findReportByToken(token);
  if (!row) notFound();

  const user = await getCurrentUser();
  // Anyone who already has full access gets the full report view instead.
  if (user && canViewReport(user, row)) redirect(`/laporan/${row.id}`);

  // Once saved to an account, the QR link stops exposing the report publicly.
  if (row.ownerId) {
    const t = (await getMessages()).account.shared;
    return (
      <main className="flex min-h-dvh flex-col items-center justify-center bg-canvas px-5 text-center">
        <Logo tone="dark" />
        <h1 className="mt-10 text-[28px] font-semibold tracking-[-0.02em] text-ink">{t.savedTitle}</h1>
        <p className="mt-3 max-w-sm text-[15px] leading-relaxed text-muted">
          {t.savedText}
        </p>
        <Button href={`/masuk?next=${encodeURIComponent(`/laporan/${row.id}`)}`} withArrow className="mt-8">
          {t.signIn}
        </Button>
      </main>
    );
  }

  return <ReportView report={toReportData(row)} mode={{ kind: 'shared', signedIn: Boolean(user) }} />;
}
