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 { getParam, type SearchParams } from "@/shared/lib/search-params"
import { getDiagnosticReports } from "@/modules/diagnostic/data-access-reports"
import { ReportList } from "@/modules/diagnostic/components/report-list"
import {
  DiagnosticServiceProvider,
} from "@/modules/diagnostic/services/diagnostic-service-context"
import {
  DiagnosticMonitorProvider,
} from "@/modules/diagnostic/services/diagnostic-monitor-context"
import type { DiagnosticReportType, DiagnosticReportStatus } from "@/modules/diagnostic/types"

export const dynamic = "force-dynamic"

const VALID_REPORT_TYPES: ReadonlySet<string> = new Set([
  "individual",
  "class",
  "grade",
])

const VALID_REPORT_STATUSES: ReadonlySet<string> = new Set([
  "draft",
  "published",
  "archived",
])

function isReportType(v: string): v is DiagnosticReportType {
  return VALID_REPORT_TYPES.has(v)
}

function isReportStatus(v: string): v is DiagnosticReportStatus {
  return VALID_REPORT_STATUSES.has(v)
}

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

  const reportTypeParam = getParam(sp, "reportType")
  const statusParam = getParam(sp, "status")

  const reportType =
    reportTypeParam && reportTypeParam !== "all" && isReportType(reportTypeParam)
      ? reportTypeParam
      : undefined
  const status =
    statusParam && statusParam !== "all" && isReportStatus(statusParam)
      ? statusParam
      : undefined

  const reports = await getDiagnosticReports({ reportType, status }, ctx.dataScope)

  // v2-P2-2: 移除客户端 filter，DataScope 过滤已在 data-access 层完成
  // class_members scope 的学生已通过 filters.studentId 在 data-access 层过滤

  // v2-P2-7: service 组装移至 DiagnosticServiceProvider（客户端），
  // 避免 server component 创建含函数的对象传给 client component。

  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("title.teacherReportList")}</h1>
        <p className="text-muted-foreground">
          {t("title.teacherReportListDesc")}
        </p>
      </div>
      <DiagnosticMonitorProvider>
        <DiagnosticServiceProvider>
          <ReportList reports={reports.reports} />
        </DiagnosticServiceProvider>
      </DiagnosticMonitorProvider>
    </div>
  )
}
