import type { Metadata } from "next";
import Link from "next/link";

import { Container } from "@/components/Container";
import { QuizRunner } from "@/components/orthoprep/QuizRunner";
import {
  getPartBySlug,
  getQuestionsByPart,
  getRandomQuestions,
  type FrcsQuestionWithContext,
} from "@/lib/frcs";

export const metadata: Metadata = {
  title: "OrthoPrep quiz session",
  description:
    "Active OrthoPrep quiz session with per-question explanations and score tracking.",
};

type SearchParams = Record<string, string | string[] | undefined>;

function firstParam(
  params: SearchParams,
  key: string,
): string | undefined {
  const v = params[key];
  if (Array.isArray(v)) return v[0];
  return v;
}

// Next.js 16 App Router passes searchParams as a Promise.
export const dynamic = "force-dynamic";

export default async function QuizSessionPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>;
}) {
  const params = await searchParams;

  const modeParam = firstParam(params, "mode") ?? "random";
  const mode: "random" | "part" = modeParam === "part" ? "part" : "random";

  let questions: FrcsQuestionWithContext[] = [];
  let partSlug: string | undefined;
  let partTitle: string | undefined;
  let retryHref = "/products/orthoprep/quiz";
  let headerLabel = "Random quiz";

  if (mode === "part") {
    partSlug = firstParam(params, "part");
    if (partSlug) {
      const summary = await getPartBySlug(partSlug);
      if (summary) {
        partTitle = summary.title;
        questions = await getQuestionsByPart(partSlug);
        headerLabel = summary.title;
        retryHref = `/products/orthoprep/quiz/session?mode=part&part=${partSlug}`;
      }
    }
  } else {
    const countRaw = Number(firstParam(params, "count") ?? "10");
    const count = Number.isFinite(countRaw)
      ? Math.max(1, Math.min(100, Math.round(countRaw)))
      : 10;
    questions = await getRandomQuestions(count);
    headerLabel = `Random · ${count}`;
    retryHref = `/products/orthoprep/quiz/session?mode=random&count=${count}`;
  }

  return (
    <section className="bg-gradient-to-b from-white via-white to-[var(--color-mist)]/40 pt-10 pb-10 md:pt-14 md:pb-14">
      <Container>
        <div className="mx-auto max-w-3xl">
          <div className="mb-8 flex flex-wrap items-center justify-between gap-3 text-[13px]">
            <Link
              href="/products/orthoprep/quiz"
              className="font-semibold text-[var(--color-blue)] underline underline-offset-2"
            >
              ← Quiz hub
            </Link>
            <span className="rounded-full border border-[var(--color-line)] bg-white px-3 py-1 text-[11px] font-bold uppercase tracking-wider text-[var(--color-slate)]">
              {headerLabel}
            </span>
          </div>

          <QuizRunner
            questions={questions}
            mode={mode}
            partSlug={partSlug}
            partTitle={partTitle}
            retryHref={retryHref}
          />
        </div>
      </Container>
    </section>
  );
}
