import type { JSX } from "react"
import { notFound } from "next/navigation"
import { ArrowLeft } from "lucide-react"
import Link from "next/link"
import { getTranslations } from "next-intl/server"
import { Button } from "@/shared/components/ui/button"
import { Badge } from "@/shared/components/ui/badge"
import { getTextbookById, getChaptersByTextbookId } from "@/modules/textbooks/data-access"
import { TeacherTextbookReader } from "./_components/teacher-textbook-reader"
import { TextbookSettingsDialog } from "@/modules/textbooks/components/textbook-settings-dialog"
import { getSubjectLabelKey, getGradeLabelKey } from "@/modules/textbooks/constants"
import { requirePermission } from "@/shared/lib/auth-guard"
import { Permissions } from "@/shared/types/permissions"

export const dynamic = "force-dynamic"

export default async function TextbookDetailPage({
  params,
}: {
  params: Promise<{ id: string }>
}): Promise<JSX.Element> {
  await requirePermission(Permissions.TEXTBOOK_READ)

  const { id } = await params
  const t = await getTranslations("textbooks")

  const [textbook, chapters] = await Promise.all([
    getTextbookById(id),
    getChaptersByTextbookId(id),
  ])

  if (!textbook) {
    notFound()
  }

  return (
    <div className="flex flex-col h-[calc(100vh-4rem)] overflow-hidden">
      {/* Header / Nav (Fixed height) */}
      <div className="flex items-center gap-4 py-4 border-b shrink-0 bg-background z-10">
        <Button asChild variant="ghost" size="sm">
          <Link href="/teacher/textbooks">
            <ArrowLeft className="mr-2 h-4 w-4" aria-hidden="true" />
            {t("reader.back")}
          </Link>
        </Button>
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 mb-1">
            <Badge variant="outline">{t(`subject.${getSubjectLabelKey(textbook.subject)}`)}</Badge>
            <span className="text-xs text-muted-foreground uppercase tracking-wider font-medium">
              {textbook.grade ? t(`grade.${getGradeLabelKey(textbook.grade)}`) : ""}
            </span>
          </div>
          <h1 className="text-xl font-bold tracking-tight line-clamp-1">{textbook.title}</h1>
        </div>
        <div className="flex gap-2">
          <TextbookSettingsDialog textbook={textbook} />
        </div>
      </div>

      {/* Main Content Layout (Flex grow) */}
      <div className="flex-1 overflow-hidden pt-6">
        <TeacherTextbookReader chapters={chapters} textbookId={id} />
      </div>
    </div>
  )
}
