import type { JSX } from "react"
import { getTeacherClasses } from "@/modules/classes/data-access"
import { getClassStudentsForEntry } from "@/modules/grades/data-access"
import { getSubjectOptions } from "@/modules/school/data-access"
import { BatchGradeEntry } from "@/modules/grades/components/batch-grade-entry"
import { getParam, type SearchParams } from "@/shared/lib/search-params"

export const dynamic = "force-dynamic"

export default async function BatchEntryPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}): Promise<JSX.Element> {
  const sp = await searchParams

  const defaultClassId = getParam(sp, "classId")
  const defaultSubjectId = getParam(sp, "subjectId")

  const [classes, allSubjects, students] = await Promise.all([
    getTeacherClasses(),
    getSubjectOptions(),
    defaultClassId
      ? getClassStudentsForEntry(defaultClassId)
      : Promise.resolve([] as Awaited<ReturnType<typeof getClassStudentsForEntry>>),
  ])

  const classOptions = classes.map((c) => ({ id: c.id, name: c.name }))
  const subjectOptions = allSubjects.map((s) => ({ id: s.id, name: s.name }))

  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">Batch Grade Entry</h1>
        <p className="text-muted-foreground">Enter grades for all students in a class at once.</p>
      </div>

      <BatchGradeEntry
        classes={classOptions}
        subjects={subjectOptions}
        students={students}
        defaultClassId={defaultClassId}
        defaultSubjectId={defaultSubjectId}
      />
    </div>
  )
}
