import type { JSX } from "react"
import { ClipboardList } from "lucide-react"

import { EmptyState } from "@/shared/components/ui/empty-state"
import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import {
  getAdminClassesForScheduling,
  getScheduleChanges,
  getTeachersForScheduling,
} from "@/modules/scheduling/data-access"
import { ScheduleChangeForm } from "@/modules/scheduling/components/schedule-change-form"
import { ScheduleChangeList } from "@/modules/scheduling/components/schedule-change-list"

export const dynamic = "force-dynamic"

export default async function TeacherScheduleChangesPage(): Promise<JSX.Element> {
  const ctx = await requirePermission(Permissions.SCHEDULE_ADJUST)

  // Teachers see only their own requests; admins landing here see all.
  const requesterId = ctx.dataScope.type === "all" ? undefined : ctx.userId

  const [classes, teachers, items] = await Promise.all([
    getAdminClassesForScheduling(),
    getTeachersForScheduling(),
    getScheduleChanges({ requesterId }),
  ])

  const classOptions = classes.map((c) => ({ id: c.id, name: c.name, grade: c.grade }))
  const teacherOptions = teachers.map((t) => ({
    id: t.id,
    name: t.name ?? "Unknown",
    email: t.email ?? "",
  }))

  return (
    <div className="flex h-full flex-col space-y-8 p-8">
      <div className="space-y-1">
        <h1 className="text-2xl font-bold tracking-tight">Schedule Change Requests</h1>
        <p className="text-muted-foreground">
          Submit a schedule change or substitute teacher request, and track its status.
        </p>
      </div>

      {classOptions.length === 0 ? (
        <EmptyState
          icon={ClipboardList}
          title="No classes available"
          description="There are no classes available to request schedule changes for."
        />
      ) : (
        <div className="space-y-8">
          <ScheduleChangeForm classes={classOptions} teachers={teacherOptions} />

          <div className="space-y-2">
            <h2 className="text-lg font-semibold">My Requests</h2>
            {items.length === 0 ? (
              <EmptyState
                icon={ClipboardList}
                title="No requests yet"
                description="Your submitted schedule change requests will appear here."
              />
            ) : (
              <ScheduleChangeList items={items} canApprove={false} />
            )}
          </div>
        </div>
      )}
    </div>
  )
}
