import type { JSX } from "react"
import { getTranslations } from "next-intl/server"
import { getTeacherClasses } from "@/modules/classes/data-access"
import { getClassAttendanceStats } from "@/modules/attendance/data-access-stats"
import { AttendanceStatsCard } from "@/modules/attendance/components/attendance-stats-card"
import { AttendanceRecordList } from "@/modules/attendance/components/attendance-record-list"
import { AttendanceStatsClassSelector } from "@/modules/attendance/components/attendance-stats-class-selector"
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 AttendanceStatsPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}): Promise<JSX.Element> {
  const t = await getTranslations("attendance")
  const sp = await searchParams

  const classId = getParam(sp, "classId")
  const startDate = getParam(sp, "startDate")
  const endDate = getParam(sp, "endDate")

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

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

      <AttendanceStatsClassSelector
        classes={classOptions}
        currentClassId={targetClassId}
        startDate={startDate ?? ""}
        endDate={endDate ?? ""}
      />

      {summary ? (
        <>
          <AttendanceStatsCard stats={summary.stats} />
          <div>
            <h2 className="mb-4 text-lg font-semibold">{t("stats.studentRecords")}</h2>
            <AttendanceRecordList records={summary.studentRecords} />
          </div>
        </>
      ) : (
        <EmptyState
          title={t("stats.noData")}
          description={t("stats.noDataDescription")}
          icon={BarChart3}
          className="border-none shadow-none"
        />
      )}
    </div>
  )
}
