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

import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { getCoursePlans } from "@/modules/course-plans/data-access"
import { CoursePlanList } from "@/modules/course-plans/components/course-plan-list"
import { getSearchParam, type SearchParams } from "@/shared/lib/utils"
import { isCoursePlanStatus } from "@/modules/course-plans/types"

export async function generateMetadata(): Promise<Metadata> {
  const t = await getTranslations("coursePlans")
  return {
    title: `${t("title")} - Next_Edu`,
    description: t("description"),
  }
}

export const dynamic = "force-dynamic"

export default async function AdminCoursePlansPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}): Promise<JSX.Element> {
  // P0-2：admin 页面补充 requirePermission 校验
  await requirePermission(Permissions.COURSE_PLAN_READ)

  const t = await getTranslations("coursePlans")
  const sp = await searchParams
  const statusParam = getSearchParam(sp, "status")
  const status = isCoursePlanStatus(statusParam) ? statusParam : undefined

  // admin 视角：scope.isAdmin = true，全局视图
  const plans = await getCoursePlans({ status }, { userId: "", isAdmin: true })

  return (
    <div className="flex h-full flex-col space-y-8 p-8">
      <div className="space-y-1">
        <h2 className="text-2xl font-bold tracking-tight">{t("title")}</h2>
        <p className="text-muted-foreground">{t("description")}</p>
      </div>
      <CoursePlanList
        plans={plans}
        canManage
        createHref="/admin/course-plans/create"
        detailBaseHref="/admin/course-plans"
        initialStatus={status}
      />
    </div>
  )
}
