import type { JSX } from "react"
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 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">Attendance Statistics</h1>
          <p className="text-muted-foreground">View class attendance statistics.</p>
        </div>
        <EmptyState
          title="No classes"
          description="You don't have any classes yet."
          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">Attendance Statistics</h1>
        <p className="text-muted-foreground">View class attendance statistics and trends.</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">Student Records</h2>
            <AttendanceRecordList records={summary.studentRecords} />
          </div>
        </>
      ) : (
        <EmptyState
          title="No data"
          description="No attendance data available for this class."
          icon={BarChart3}
          className="border-none shadow-none"
        />
      )}
    </div>
  )
}
