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

import { Button } from "@/shared/components/ui/button"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { requirePermission, getAuthContext } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { getSearchParam, type SearchParams } from "@/shared/lib/utils"
import { getAdminClasses } from "@/modules/classes/data-access"
import { getGrades } from "@/modules/school/data-access"
import { getAttendanceRecords, getAttendanceStats } from "@/modules/attendance/data-access"
import { getClassComparison } from "@/modules/attendance/data-access-stats"
import { getAttendanceGradeCorrelation } from "@/modules/attendance/data-access-correlation"
import { AttendanceFilters } from "@/modules/attendance/components/attendance-filters"
import { AttendanceStatsCards } from "@/modules/attendance/components/attendance-stats-cards"
import { AttendanceRecordList } from "@/modules/attendance/components/attendance-record-list"
import { AttendancePageLayout } from "@/modules/attendance/components/attendance-page-layout"
import { ClassComparisonCard } from "@/modules/attendance/components/class-comparison-card"
import { AttendanceGradeCorrelationCard } from "@/modules/attendance/components/attendance-grade-correlation-card"
import type { AttendanceStatus } from "@/modules/attendance/types"

export const dynamic = "force-dynamic"

const isValidAttendanceStatus = (v?: string): v is AttendanceStatus =>
  v === "present" || v === "absent" || v === "late" || v === "early_leave" || v === "excused" || v === "school_activity"

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

  const classId = getSearchParam(sp, "classId")
  const statusParam = getSearchParam(sp, "status")
  const status =
    statusParam && statusParam !== "all" && isValidAttendanceStatus(statusParam) ? statusParam : undefined
  const date = getSearchParam(sp, "date")
  // L-7：跨班级对比的年级选择
  const gradeId = getSearchParam(sp, "gradeId")
  const startDate = getSearchParam(sp, "startDate")
  const endDate = getSearchParam(sp, "endDate")

  const classes = await getAdminClasses()
  const classOptions = classes.map((c) => ({ id: c.id, name: c.name }))

  // 并行获取：记录、统计、年级列表、对比汇总
  const [result, stats, grades, comparison, correlation] = await Promise.all([
    getAttendanceRecords({
      scope: ctx.dataScope,
      currentUserId: ctx.userId,
      classId: classId && classId !== "all" ? classId : undefined,
      status,
      date: date && date.length > 0 ? date : undefined,
    }),
    getAttendanceStats({
      scope: ctx.dataScope,
      currentUserId: ctx.userId,
      classId: classId && classId !== "all" ? classId : undefined,
      date: date && date.length > 0 ? date : undefined,
    }),
    getGrades(),
    // L-7：若指定 gradeId 则获取对比汇总
    gradeId
      ? getClassComparison(gradeId, startDate ?? undefined, endDate ?? undefined)
      : Promise.resolve(null),
    // L-9：考勤-成绩关联分析（仅当指定班级时）
    classId && classId !== "all"
      ? getAttendanceGradeCorrelation(
          classId,
          startDate ?? undefined,
          endDate ?? undefined,
          ctx.dataScope
        )
      : Promise.resolve(null),
  ])

  const gradeOptions = grades.map((g) => ({ id: g.id, name: g.name }))

  const header = (
    <div className="flex items-center justify-between space-y-2">
      <div>
        <h2 className="text-2xl font-bold tracking-tight">{t("title.adminOverview")}</h2>
        <p className="text-muted-foreground">{t("description.adminOverview")}</p>
      </div>
      <Button asChild variant="outline">
        <Link href="/teacher/attendance/stats">
          <BarChart3 className="mr-2 h-4 w-4" />
          {t("actions.stats")}
        </Link>
      </Button>
    </div>
  )

  return (
    <AttendancePageLayout
      header={header}
      stats={<AttendanceStatsCards stats={stats} />}
      filters={<AttendanceFilters classes={classOptions} />}
    >
      <div className="space-y-6">
        {result.items.length === 0 && !classId && !status && !date ? (
          <EmptyState
            title={t("list.empty")}
            description={t("list.emptyDescription")}
            icon={ClipboardList}
          />
        ) : (
          <AttendanceRecordList records={result.items} />
        )}

        <ClassComparisonCard
          summary={comparison}
          grades={gradeOptions}
          currentGradeId={gradeId ?? undefined}
        />

        {/* L-9：考勤与成绩关联分析（仅当指定班级时显示） */}
        {classId && classId !== "all" && (
          <AttendanceGradeCorrelationCard summary={correlation} />
        )}
      </div>
    </AttendancePageLayout>
  )
}

