import type { Metadata } from "next";
import { notFound, redirect } from "next/navigation";
import { requireUser } from "@/lib/auth/rbac";
import { getActiveAttempt, getStudentQuiz } from "@/lib/queries/quizzes";
import { PageHeader } from "@/components/ui/page-header";
import { QuizRunner, ExpiredAttemptNotice } from "@/components/quizzes/quiz-runner";
import { routeCrumbs } from "@/lib/breadcrumbs";

/**
 * The paper itself.
 *
 * A timed attempt whose clock has already run out gets the notice instead of
 * the paper: showing the questions again would invite a student to answer a
 * quiz they no longer have time for, and the server would reject the
 * submission anyway.
 */

export const metadata: Metadata = { title: "Mengerjakan Kuis" };

export default async function AttemptPage({
  params,
}: {
  params: Promise<{ assignmentId: string }>;
}) {
  const { assignmentId } = await params;
  const user = await requireUser(`/dashboard/quizzes/${assignmentId}/kerjakan`);

  if (user.role === "ADMIN" || user.role === "TEACHER") {
    redirect(`/dashboard/quizzes/${assignmentId}/kelola`);
  }

  const quiz = await getStudentQuiz({ userId: user.id, role: user.role }, assignmentId);
  if (!quiz) notFound();

  // No open attempt: the lobby is the right place, not an error page. This is
  // what a student sees after a refresh once they have already handed in.
  if (!quiz.activeAttemptId) {
    redirect(`/dashboard/quizzes/${assignmentId}`);
  }

  const attempt = await getActiveAttempt(
    { userId: user.id, role: user.role },
    quiz.activeAttemptId
  );

  if (!attempt) {
    redirect(`/dashboard/quizzes/${assignmentId}`);
  }

  const expired = attempt.secondsRemaining !== null && attempt.secondsRemaining <= 0;

  return (
    <div className="space-y-6">
      <PageHeader
        folio="TC/LMS-16"
        crumbs={routeCrumbs(`/dashboard/quizzes/${assignmentId}/kerjakan`, attempt.assignmentTitle, [
          { label: quiz.courseTitle, href: `/dashboard/courses/${quiz.courseId}` },
          { label: "Kuis", href: `/dashboard/quizzes/${assignmentId}` },
        ])}
        title={attempt.assignmentTitle}
        description={`${attempt.courseTitle} · percobaan ${attempt.attemptNo}`}
      />

      {expired ? <ExpiredAttemptNotice attempt={attempt} /> : <QuizRunner attempt={attempt} />}
    </div>
  );
}
