import type { JSX } from "react"
import { Suspense } from "react"
import { Calendar } from "lucide-react"

import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { getClassSchedule, getTeacherClasses } from "@/modules/classes/data-access"
import { ScheduleFilters } from "@/modules/classes/components/schedule-filters"
import { ScheduleView } from "@/modules/classes/components/schedule-view"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { Skeleton } from "@/shared/components/ui/skeleton"
import { getParam, type SearchParams } from "@/shared/lib/search-params"

export const dynamic = "force-dynamic"

async function ScheduleResults({ searchParams }: { searchParams: Promise<SearchParams> }): Promise<JSX.Element> {
  const params = await searchParams
  const classId = getParam(params, "classId")

  const classes = await getTeacherClasses()
  const schedule = await getClassSchedule({
    classId: classId && classId !== "all" ? classId : undefined,
  })

  const hasFilters = Boolean(classId && classId !== "all")

  if (schedule.length === 0) {
    return (
      <EmptyState
        icon={Calendar}
        title={hasFilters ? "No schedule for this class" : "No schedule available"}
        description={hasFilters ? "Try selecting another class." : "Your class schedule has not been set up yet."}
        action={hasFilters ? { label: "Clear filters", href: "/teacher/classes/schedule" } : undefined}
        className="h-[360px] bg-card"
      />
    )
  }

  return <ScheduleView schedule={schedule} classes={classes} />
}

function ScheduleResultsFallback() {
  return (
    <div className="grid gap-6 md:grid-cols-2 xl:grid-cols-3">
      {Array.from({ length: 6 }).map((_, idx) => (
        <div key={idx} className="rounded-lg border bg-card p-6">
          <div className="flex items-center justify-between">
            <Skeleton className="h-5 w-16" />
            <Skeleton className="h-5 w-20" />
          </div>
          <div className="mt-6 space-y-3">
            <Skeleton className="h-4 w-[70%]" />
            <Skeleton className="h-4 w-[85%]" />
            <Skeleton className="h-4 w-[60%]" />
          </div>
        </div>
      ))}
    </div>
  )
}

export default async function SchedulePage({ searchParams }: { searchParams: Promise<SearchParams> }): Promise<JSX.Element> {
  await requirePermission(Permissions.CLASS_READ)
  const classes = await getTeacherClasses()

  return (
    <div className="flex h-full flex-col space-y-8 p-8">
      <div className="space-y-6">
        <Suspense fallback={<div className="h-10 w-full animate-pulse rounded-md bg-muted" />}>
          <ScheduleFilters classes={classes} />
        </Suspense>

        <Suspense fallback={<ScheduleResultsFallback />}>
          <ScheduleResults searchParams={searchParams} />
        </Suspense>
      </div>
    </div>
  )
}
