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

import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"
import { getParam, type SearchParams } from "@/shared/lib/search-params"
import { Skeleton } from "@/shared/components/ui/skeleton"
import { WidgetBoundary } from "@/shared/components/widget-boundary"

import { getErrorBookItems, getErrorBookStats } from "@/modules/error-book/data-access"
import { ErrorBookStatsCards } from "@/modules/error-book/components/error-book-stats-cards"
import { ErrorBookFilters } from "@/modules/error-book/components/error-book-filters"
import type { ErrorBookStatusValue, ErrorBookSourceTypeValue } from "@/modules/error-book/types"
import {
  AiClientProvider,
} from "@/modules/ai/context/ai-client-provider"
import { createCoreAiClientService } from "@/modules/ai/context/create-ai-client-service"
import { StudentErrorBookListClient } from "./student-error-book-list-client"
import { AddErrorBookDialogWithQuestions } from "./add-error-book-dialog-with-questions"

export const dynamic = "force-dynamic"

const VALID_STATUS = new Set(["new", "learning", "mastered", "archived"])
const VALID_SOURCE = new Set(["exam", "homework", "manual"])

function isErrorBookStatus(v: string): v is ErrorBookStatusValue {
  return VALID_STATUS.has(v)
}

function isErrorBookSource(v: string): v is ErrorBookSourceTypeValue {
  return VALID_SOURCE.has(v)
}

function parseStatus(v?: string): ErrorBookStatusValue | undefined {
  if (!v || !isErrorBookStatus(v)) return undefined
  return v
}

function parseSource(v?: string): ErrorBookSourceTypeValue | undefined {
  if (!v || !isErrorBookSource(v)) return undefined
  return v
}

async function ErrorBookResults({ searchParams }: { searchParams: Promise<SearchParams> }): Promise<JSX.Element> {
  const params = await searchParams
  const ctx = await requirePermission(Permissions.ERROR_BOOK_READ)

  const q = getParam(params, "q")
  const status = parseStatus(getParam(params, "status"))
  const sourceType = parseSource(getParam(params, "source"))
  const dueOnly = getParam(params, "due") === "due"

  const { data: items } = await getErrorBookItems({
    studentId: ctx.userId,
    q: q || undefined,
    status,
    sourceType,
    dueOnly,
    pageSize: 50,
  })

  return <StudentErrorBookListClient items={items} studentId={ctx.userId} />
}

function ErrorBookResultsFallback() {
  return (
    <div className="grid gap-3 md:grid-cols-2">
      {Array.from({ length: 4 }).map((_, idx) => (
        <Skeleton key={idx} className="h-[180px] w-full rounded-md" />
      ))}
    </div>
  )
}

export default async function StudentErrorBookPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}): Promise<JSX.Element> {
  const ctx = await requirePermission(Permissions.ERROR_BOOK_READ)
  const t = await getTranslations("student")
  const stats = await getErrorBookStats(ctx.userId)
  const aiClientService = createCoreAiClientService()

  return (
    <AiClientProvider service={aiClientService}>
      <div className="flex h-full flex-col space-y-8 p-8">
        <div className="flex flex-col justify-between space-y-4 md:flex-row md:items-center md:space-y-0">
          <div>
            <h1 className="text-2xl font-bold tracking-tight">{t("errorBook.title")}</h1>
            <p className="text-muted-foreground">
              {t("errorBook.description")}
            </p>
          </div>
          <div className="flex items-center gap-2">
            <AddErrorBookDialogWithQuestions />
          </div>
        </div>

        <WidgetBoundary title={t("errorBook.title")} skeletonHeight={120}>
          <ErrorBookStatsCards stats={stats} />
        </WidgetBoundary>

        <div className="space-y-4">
          <Suspense fallback={<div className="h-10 w-full animate-pulse rounded-md bg-muted" />}>
            <ErrorBookFilters />
          </Suspense>

          <WidgetBoundary title={t("errorBook.title")} skeletonHeight={360}>
            <Suspense fallback={<ErrorBookResultsFallback />}>
              <ErrorBookResults searchParams={searchParams} />
            </Suspense>
          </WidgetBoundary>
        </div>
      </div>
    </AiClientProvider>
  )
}
