import type { JSX } from "react"
import { notFound } from "next/navigation"
import { ArrowLeft } from "lucide-react"
import Link from "next/link"
import { Button } from "@/shared/components/ui/button"
import { Badge } from "@/shared/components/ui/badge"
import { getTextbookById, getChaptersByTextbookId, getKnowledgePointsByTextbookId } from "@/modules/textbooks/data-access"
import { TextbookReader } from "@/modules/textbooks/components/textbook-reader"
import { TextbookSettingsDialog } from "@/modules/textbooks/components/textbook-settings-dialog"

export const dynamic = "force-dynamic"

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

  const [textbook, chapters, knowledgePoints] = await Promise.all([
    getTextbookById(id),
    getChaptersByTextbookId(id),
    getKnowledgePointsByTextbookId(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" />
            返回教材列表
          </Link>
        </Button>
        <div className="flex-1 min-w-0">
          <div className="flex items-center gap-2 mb-1">
            <Badge variant="outline">{textbook.subject}</Badge>
            <span className="text-xs text-muted-foreground uppercase tracking-wider font-medium">
              {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">
        <TextbookReader
          chapters={chapters}
          knowledgePoints={knowledgePoints}
          textbookId={id}
          canEdit={true}
        />
      </div>
    </div>
  )
}
