import type { JSX } from "react"
import { notFound } from "next/navigation"
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> {
  try {
    await requirePermission(Permissions.EXAM_PROCTOR)
  } catch (error) {
    if (error instanceof PermissionDeniedError) {
      return (
        <div className="p-10 text-center text-muted-foreground">
          您没有监考权限（exam:proctor）。
        </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">Exam Proctoring</h1>
        <p className="text-muted-foreground">Monitor student activity during the exam.</p>
      </div>
      <ProctoringDashboard examId={id} initialData={initialData} />
    </div>
  )
}
