import { UserX } from "lucide-react"

import { getStudentClasses, getStudentSchedule } from "@/modules/classes/data-access"
import { getCurrentStudentUser } from "@/modules/users/data-access"
import { StudentScheduleFilters } from "@/modules/student/components/student-schedule-filters"
import { StudentScheduleView } from "@/modules/student/components/student-schedule-view"
import { EmptyState } from "@/shared/components/ui/empty-state"

export const dynamic = "force-dynamic"

type SearchParams = { [key: string]: string | string[] | undefined }

export default async function StudentSchedulePage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}) {
  const student = await getCurrentStudentUser()
  if (!student) {
    return (
      <div className="h-full flex-1 flex-col space-y-8 p-8 md:flex">
        <div>
          <h2 className="text-2xl font-bold tracking-tight">Schedule</h2>
          <p className="text-muted-foreground">Your weekly timetable.</p>
        </div>
        <EmptyState title="No user found" description="Create a student user to see schedule." icon={UserX} />
      </div>
    )
  }

  const [sp, classes, schedule] = await Promise.all([
    searchParams,
    getStudentClasses(student.id),
    getStudentSchedule(student.id),
  ])

  const classIdParam = sp.classId
  const resolveClassId = (param: string | string[] | undefined): string => {
    if (typeof param === "string") return param
    if (Array.isArray(param)) return param[0] ?? "all"
    return "all"
  }
  const classId = resolveClassId(classIdParam)
  const filteredItems =
    classId !== "all" ? schedule.filter((s) => s.classId === classId) : schedule

  return (
    <div className="flex h-full flex-col space-y-8 p-8">
      <div className="flex flex-col justify-between gap-4 md:flex-row md:items-center">
        <div>
          <h2 className="text-2xl font-bold tracking-tight">Schedule</h2>
          <p className="text-muted-foreground">Your weekly timetable.</p>
        </div>
        <StudentScheduleFilters classes={classes} />
      </div>
      <StudentScheduleView items={filteredItems} />
    </div>
  )
}

