import Link from "next/link"
import { PlusCircle, ClipboardList } from "lucide-react"
import type { Metadata } from "next"
import type { JSX } from "react"

import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { Button } from "@/shared/components/ui/button"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { getSearchParam, type SearchParams } from "@/shared/lib/utils"
import {
  getAdminClassesForScheduling,
  getScheduleChanges,
  getScheduleEntriesForAdmin,
} from "@/modules/scheduling/data-access"
import { ScheduleChangeList } from "@/modules/scheduling/components/schedule-change-list"
import { ScheduleConflictsView } from "@/modules/scheduling/components/schedule-conflicts-view"
import { ScheduleGridView } from "@/modules/scheduling/components/schedule-grid-view"
import type { ScheduleChangeStatus } from "@/modules/scheduling/types"

export const metadata: Metadata = {
  title: "课表变更申请 - Next_Edu",
  description: "审核、批准或拒绝课表变更与代课申请",
}

export const dynamic = "force-dynamic"

const isValidStatus = (v?: string): v is ScheduleChangeStatus =>
  v === "pending" || v === "approved" || v === "rejected" || v === "completed"

export default async function AdminSchedulingChangesPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}): Promise<JSX.Element> {
  await requirePermission(Permissions.SCHEDULE_ADJUST)
  const sp = await searchParams
  const statusParam = getSearchParam(sp, "status")
  const status = isValidStatus(statusParam) ? statusParam : undefined
  const classIdParam = getSearchParam(sp, "classId")
  const classId = classIdParam && classIdParam !== "all" ? classIdParam : undefined

  const [classes, items, scheduleEntries] = await Promise.all([
    getAdminClassesForScheduling(),
    getScheduleChanges({ status, classId }),
    getScheduleEntriesForAdmin(),
  ])
  const classOptions = classes.map((c) => ({ id: c.id, name: c.name, grade: c.grade }))

  return (
    <div className="flex h-full flex-col space-y-8 p-8">
      <div className="flex items-center justify-between space-y-2">
        <div className="space-y-1">
          <h2 className="text-2xl font-bold tracking-tight">课表变更申请</h2>
          <p className="text-muted-foreground">
            审核、批准或拒绝课表变更与代课申请。
          </p>
        </div>
        <Button asChild>
          <Link href="/teacher/schedule-changes">
            <PlusCircle className="mr-2 h-4 w-4" />
            新建申请
          </Link>
        </Button>
      </div>

      {items.length === 0 && !status && !classId ? (
        <EmptyState
          icon={ClipboardList}
          title="暂无课表变更申请"
          description="系统中尚未产生任何课表变更申请。"
          action={{
            label: "新建申请",
            href: "/teacher/schedule-changes",
          }}
        />
      ) : (
        <ScheduleChangeList items={items} canApprove />
      )}

      <div className="space-y-2">
        <h3 className="text-lg font-semibold">冲突检测</h3>
        <p className="text-sm text-muted-foreground">
          检测现有班级课表中的时间重叠。
        </p>
        {classOptions.length === 0 ? (
          <EmptyState
            icon={ClipboardList}
            title="暂无可用班级"
            description="请先创建班级，再进行冲突检测。"
          />
        ) : (
          <ScheduleConflictsView classes={classOptions} />
        )}
      </div>

      <div className="space-y-2">
        <h3 className="text-lg font-semibold">课表网格</h3>
        <p className="text-sm text-muted-foreground">
          按班级查看当前课表分布。
        </p>
        <ScheduleGridView entries={scheduleEntries} classes={classOptions} />
      </div>
    </div>
  )
}
