import type { JSX } from "react"
import { getTeacherClasses, getClassGradeIdsByClassIds } from "@/modules/classes/data-access"
import { getClassStudentsForEntry } from "@/modules/grades/data-access"
import { getExamsForGradeEntry, getExamForGradeEntry } from "@/modules/exams/data-access"
import { BatchGradeEntryByExam } from "@/modules/grades/components/batch-grade-entry"
import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { getParam, type SearchParams } from "@/shared/lib/search-params"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { ClipboardList } from "lucide-react"
import { getTranslations } from "next-intl/server"

export const dynamic = "force-dynamic"

export default async function BatchEntryPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}): Promise<JSX.Element> {
  const ctx = await requirePermission(Permissions.GRADE_RECORD_MANAGE)
  const sp = await searchParams
  const t = await getTranslations("grades")

  const examId = getParam(sp, "examId")
  const classId = getParam(sp, "classId")

  // 获取试卷列表 + 班级列表
  const [exams, teacherClasses] = await Promise.all([
    getExamsForGradeEntry(ctx.dataScope),
    getTeacherClasses(),
  ])

  // scope 过滤班级
  const allowedClassIds =
    ctx.dataScope.type === "class_taught" ? ctx.dataScope.classIds : null
  const scopedClasses = allowedClassIds
    ? teacherClasses.filter((c) => allowedClassIds.includes(c.id))
    : teacherClasses

  const classOptions = scopedClasses.map((c) => ({ id: c.id, name: c.name }))

  // 获取 classId → gradeId 映射（用于客户端按试卷年级过滤班级）
  const classGradeMap: Record<string, string> = {}
  if (scopedClasses.length > 0) {
    const gradeMap = await getClassGradeIdsByClassIds(
      scopedClasses.map((c) => c.id)
    )
    for (const [cid, gid] of gradeMap.entries()) {
      classGradeMap[cid] = gid
    }
  }

  // 如果有 examId，获取试卷详情（含题目列表）
  const exam = examId
    ? await getExamForGradeEntry(examId, ctx.dataScope)
    : null

  // 如果有 examId + classId，获取学生列表
  const students =
    examId && classId
      ? await getClassStudentsForEntry(classId, ctx.dataScope)
      : []

  return (
    <div className="h-full flex-1 flex-col space-y-8 p-8 md:flex">
      <div>
        <h1 className="text-2xl font-bold tracking-tight">{t("page.entry.title")}</h1>
        <p className="text-muted-foreground">{t("page.entry.description")}</p>
      </div>

      {exams.length === 0 ? (
        <EmptyState
          title={t("page.entry.noExamsTitle")}
          description={t("page.entry.noExamsDescription")}
          icon={ClipboardList}
          className="border-none shadow-none"
        />
      ) : (
        <BatchGradeEntryByExam
          exams={exams}
          classes={classOptions}
          classGradeMap={classGradeMap}
          exam={exam}
          students={students}
          defaultExamId={examId}
          defaultClassId={classId}
        />
      )}
    </div>
  )
}
