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 { getPracticeSessions, getPracticeStats } from "@/modules/adaptive-practice/data-access"
import { PracticeStarterWithNav } from "@/modules/adaptive-practice/components/practice-starter-with-nav"
import { PracticeHistory } from "@/modules/adaptive-practice/components/practice-history"
import { PracticeStatsCards } from "@/modules/adaptive-practice/components/practice-stats-cards"
import { PracticeServiceProvider } from "@/modules/adaptive-practice/services/practice-service"
import { getKnowledgePointOptions } from "@/modules/questions/data-access"

export const dynamic = "force-dynamic"

export default async function StudentPracticePage(): Promise<JSX.Element> {
  const ctx = await requirePermission(Permissions.ADAPTIVE_PRACTICE_READ)
  const t = await getTranslations("practice")

  const [stats, sessionsResult, knowledgePoints] = await Promise.all([
    getPracticeStats(ctx.userId),
    getPracticeSessions(ctx.userId, { pageSize: 20 }),
    getKnowledgePointOptions(),
  ])

  return (
    <PracticeServiceProvider>
      <div className="flex h-full flex-col space-y-8 p-8">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">{t("page.title")}</h1>
          <p className="text-muted-foreground">{t("page.description")}</p>
        </div>

        <PracticeStatsCards stats={stats} />

        <div className="grid gap-6 lg:grid-cols-3">
          <div className="lg:col-span-1">
            <PracticeStarterWithNav
              knowledgePoints={knowledgePoints}
              routePrefix="/student/practice"
            />
          </div>
          <div className="lg:col-span-2 space-y-4">
            <h2 className="text-lg font-semibold">{t("history.title")}</h2>
            <PracticeHistory
              sessions={sessionsResult.data}
              routePrefix="/student/practice"
            />
          </div>
        </div>
      </div>
    </PracticeServiceProvider>
  )
}
