import type { JSX } from "react"
import { ArrowLeft } from "lucide-react"
import Link from "next/link"
import { getTranslations } from "next-intl/server"

import { Button } from "@/shared/components/ui/button"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { getParam, type SearchParams } from "@/shared/lib/search-params"

import { getReportCardData } from "@/modules/grades/lib/report-card"
import { ReportCardView } from "@/modules/grades/components/report-card-view"
import { ReportCardPrintAction } from "@/modules/grades/components/report-card-print-action"
import { getAcademicYears } from "@/modules/school/data-access"

export const dynamic = "force-dynamic"

/**
 * P3-1: 教师视角的学生成绩报告卡页面。
 *
 * 路由：/teacher/grades/report-card?studentId=xxx
 * 查询参数：
 *   - studentId: 必填，目标学生 ID
 *   - academicYearId?: 指定学年（不传则使用当前活跃学年）
 *   - semester?: "1" | "2"（不传则全部学期）
 *
 * 权限：GRADE_RECORD_READ（class_taught scope 在 data-access 层校验学生归属）
 */
export default async function TeacherReportCardPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}): Promise<JSX.Element> {
  const sp = await searchParams
  const ctx = await requirePermission(Permissions.GRADE_RECORD_READ)
  const t = await getTranslations("grades")

  const studentId = getParam(sp, "studentId")
  const academicYearIdParam = getParam(sp, "academicYearId")
  const semesterParam = getParam(sp, "semester")
  const academicYearId =
    academicYearIdParam && academicYearIdParam !== "all"
      ? academicYearIdParam
      : undefined
  const semester =
    semesterParam === "1" || semesterParam === "2" ? semesterParam : undefined

  if (!studentId) {
    return (
      <div className="h-full flex-1 flex-col space-y-6 p-8 md:flex">
        <Button asChild variant="ghost" size="sm" className="w-fit">
          <Link href="/teacher/grades">
            <ArrowLeft className="mr-2 h-4 w-4" aria-hidden="true" />
            {t("reportCard.backToGrades")}
          </Link>
        </Button>
        <EmptyState
          title={t("reportCard.missingStudentTitle")}
          description={t("reportCard.missingStudentDescription")}
          icon={ArrowLeft}
          className="border-none shadow-none"
        />
      </div>
    )
  }

  const [data, academicYears] = await Promise.all([
    getReportCardData(studentId, ctx.dataScope, {
      academicYearId,
      semester,
    }),
    getAcademicYears(),
  ])

  if (!data) {
    return (
      <div className="h-full flex-1 flex-col space-y-6 p-8 md:flex">
        <Button asChild variant="ghost" size="sm" className="w-fit">
          <Link href="/teacher/grades">
            <ArrowLeft className="mr-2 h-4 w-4" aria-hidden="true" />
            {t("reportCard.backToGrades")}
          </Link>
        </Button>
        <EmptyState
          title={t("reportCard.emptyTitle")}
          description={t("reportCard.emptyDescription")}
          icon={ArrowLeft}
          className="border-none shadow-none"
        />
      </div>
    )
  }

  return (
    <div className="flex flex-col gap-4 p-6">
      <div className="flex items-center justify-between gap-4">
        <Button asChild variant="ghost" size="sm">
          <Link href="/teacher/grades">
            <ArrowLeft className="mr-2 h-4 w-4" aria-hidden="true" />
            {t("reportCard.backToGrades")}
          </Link>
        </Button>
        <ReportCardPrintAction />
      </div>

      <ReportCardView data={data} />

      <p className="text-center text-xs text-muted-foreground">
        {t("reportCard.academicYearsCount", {
          count: academicYears.length,
        })}
      </p>
    </div>
  )
}
