import type { JSX } from "react"
import { getTranslations } from "next-intl/server"
import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { getTeacherClasses } from "@/modules/classes/data-access"
import { getClassAttendanceStats } from "@/modules/attendance/data-access-stats"
import { AttendanceReportPrint } from "@/modules/attendance/components/attendance-report-print"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { getParam, type SearchParams } from "@/shared/lib/search-params"
import { BarChart3 } from "lucide-react"

export const dynamic = "force-dynamic"

export default async function AttendanceReportPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}): Promise<JSX.Element> {
  await requirePermission(Permissions.ATTENDANCE_READ)
  const t = await getTranslations("attendance")
  const sp = await searchParams

  const classId = getParam(sp, "classId")
  const startDate = getParam(sp, "startDate")
  const endDate = getParam(sp, "endDate")
  // L-8：报告类型（weekly 默认 / monthly）
  const reportType = getParam(sp, "reportType") === "monthly" ? "monthly" : "weekly"

  const classes = await getTeacherClasses()

  if (classes.length === 0) {
    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("report.title")}</h1>
          <p className="text-muted-foreground">{t("report.description")}</p>
        </div>
        <EmptyState
          title={t("stats.noClasses")}
          description={t("stats.noClassesDescription")}
          icon={BarChart3}
          className="border-none shadow-none"
        />
      </div>
    )
  }

  const targetClassId = classId ?? classes[0].id

  const summary = await getClassAttendanceStats(
    targetClassId,
    startDate,
    endDate
  )

  const classOptions = classes.map((c) => ({ id: c.id, name: c.name }))
  const targetClass = classes.find((c) => c.id === targetClassId)

  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("report.title")}</h1>
        <p className="text-muted-foreground">{t("report.description")}</p>
      </div>

      <AttendanceReportPrint
        summary={summary}
        classes={classOptions}
        currentClassId={targetClassId}
        currentClassName={targetClass?.name ?? ""}
        startDate={startDate ?? ""}
        endDate={endDate ?? ""}
        reportType={reportType}
      />
    </div>
  )
}
