import type { JSX } from "react"
import { getAuthContext } from "@/shared/lib/auth-guard"
import { getParam, type SearchParams } from "@/shared/lib/search-params"
import { getCoursePlans } from "@/modules/course-plans/data-access"
import { CoursePlanList } from "@/modules/course-plans/components/course-plan-list"
import type { CoursePlanStatus } from "@/modules/course-plans/types"

export const dynamic = "force-dynamic"

const VALID_STATUSES: ReadonlySet<string> = new Set([
  "planning",
  "active",
  "completed",
  "paused",
])

function parseStatus(v?: string): CoursePlanStatus | undefined {
  return v && VALID_STATUSES.has(v) ? (v as CoursePlanStatus) : undefined
}

export default async function TeacherCoursePlansPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}): Promise<JSX.Element> {
  const ctx = await getAuthContext()
  const teacherId = ctx.userId

  const sp = await searchParams
  const statusParam = getParam(sp, "status")
  const status = parseStatus(statusParam)

  const plans = teacherId
    ? await getCoursePlans({ teacherId, status })
    : []

  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">My Course Plans</h1>
        <p className="text-muted-foreground">
          View your course teaching plans and weekly schedules.
        </p>
      </div>
      <CoursePlanList
        plans={plans}
        detailBaseHref="/teacher/course-plans"
        initialStatus={status}
      />
    </div>
  )
}
