import type { Metadata } from "next"
import type { JSX } from "react"
import { getTranslations } from "next-intl/server"

import { getElectiveCourses } from "@/modules/elective/data-access"
import { ElectiveCourseList } from "@/modules/elective/components/elective-course-list"
import { ElectivePageLayout } from "@/modules/elective/components/elective-page-layout"
import { getSearchParam, type SearchParams } from "@/shared/lib/utils"
import type { ElectiveCourseStatus } from "@/modules/elective/types"

export const dynamic = "force-dynamic"

const isValidStatus = (v?: string): v is ElectiveCourseStatus =>
  v === "draft" || v === "open" || v === "closed" || v === "cancelled"

export default async function AdminElectivePage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}): Promise<JSX.Element> {
  const sp = await searchParams
  const t = await getTranslations("elective")
  const statusParam = getSearchParam(sp, "status")
  const status = isValidStatus(statusParam) ? statusParam : undefined

  const courses = await getElectiveCourses({ status })

  const header = (
    <div className="space-y-1">
      <h2 className="text-2xl font-bold tracking-tight">{t("title.adminList")}</h2>
      <p className="text-muted-foreground">
        {t("description.adminList")}
      </p>
    </div>
  )

  return (
    <ElectivePageLayout header={header}>
      <ElectiveCourseList
        courses={courses}
        canManage
        createHref="/admin/elective/create"
        editBaseHref="/admin/elective"
      />
    </ElectivePageLayout>
  )
}
