import type { JSX } from "react"
import { notFound } from "next/navigation"
import { getTranslations } from "next-intl/server"
import { requirePermission, PermissionDeniedError } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { ProctoringDashboard } from "@/modules/proctoring/components/proctoring-dashboard"
import {
  getExamForProctoring,
  getExamProctoringSummary,
  getStudentProctoringStatuses,
  getRecentProctoringEvents,
} from "@/modules/proctoring/data-access"
import type { ProctoringDashboardData } from "@/modules/proctoring/types"

export const dynamic = "force-dynamic"

export default async function ExamProctoringPage({
  params,
}: {
  params: Promise<{ id: string }>
}): Promise<JSX.Element> {
  const t = await getTranslations("examHomework.proctoring.page")
  try {
    await requirePermission(Permissions.EXAM_PROCTOR)
  } catch (error) {
    if (error instanceof PermissionDeniedError) {
      return (
        <div className="p-10 text-center text-muted-foreground">
          {t("noPermission")}
        </div>
      )
    }
    throw error
  }

  const { id } = await params
  const exam = await getExamForProctoring(id)
  if (!exam) return notFound()

  // 并行拉取面板初始数据
  const [summary, students, recentEvents] = await Promise.all([
    getExamProctoringSummary(id),
    getStudentProctoringStatuses(id),
    getRecentProctoringEvents(id, 20),
  ])

  const initialData: ProctoringDashboardData = {
    summary,
    students,
    recentEvents,
  }

  return (
    <div className="flex h-full flex-col space-y-4 p-4">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">{t("title")}</h1>
        <p className="text-muted-foreground">{t("description")}</p>
      </div>
      <ProctoringDashboard examId={id} initialData={initialData} />
    </div>
  )
}
