import type { JSX } from "react"
import { Suspense } from "react"
import { BookX, Clock, GraduationCap, Repeat, Sparkles } from "lucide-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 { StatsGrid } from "@/shared/components/ui/stats-grid"
import { WidgetBoundary } from "@/shared/components/widget-boundary"

import { getErrorBookItems, getErrorBookStats } from "@/modules/error-book/data-access"
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"
import { ErrorBookFilters } from "./error-book-filters"

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 tStats = await getTranslations("errorBook")
  const masteredPercent = stats.totalCount > 0
    ? Math.round(stats.masteredRate * 100)
    : 0
  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}>
          <StatsGrid
            columns={5}
            items={[
              { label: tStats("stats.total"), value: stats.totalCount, icon: BookX, description: tStats("stats.totalDesc") },
              { label: tStats("stats.new"), value: stats.newCount, icon: Sparkles, color: "text-blue-500", description: tStats("stats.newDesc") },
              { label: tStats("stats.learning"), value: stats.learningCount, icon: Repeat, color: "text-amber-500", description: tStats("stats.learningDesc") },
              { label: tStats("stats.mastered"), value: stats.masteredCount, icon: GraduationCap, color: "text-emerald-500", description: tStats("stats.masteredDesc", { rate: masteredPercent }) },
              { label: tStats("stats.dueReview"), value: stats.dueReviewCount, icon: Clock, color: "text-rose-500", description: tStats("stats.dueReviewDesc"), highlight: stats.dueReviewCount > 0 },
            ]}
          />
        </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>
  )
}
