import { notFound } from "next/navigation"

import { BookOpen, Inbox } from "lucide-react"

import { getTextbookById, getChaptersByTextbookId, getKnowledgePointsByTextbookId } from "@/modules/textbooks/data-access"
import { TextbookReader } from "@/modules/textbooks/components/textbook-reader"
import { Badge } from "@/shared/components/ui/badge"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { getDemoStudentUser } from "@/modules/homework/data-access"

export const dynamic = "force-dynamic"

export default async function StudentTextbookDetailPage({
  params,
}: {
  params: Promise<{ id: string }>
}) {
  const student = await getDemoStudentUser()
  if (!student) {
    return (
      <div className="h-full flex-1 flex-col space-y-8 p-8 md:flex">
        <div className="flex items-center justify-between space-y-2">
          <div>
            <h2 className="text-2xl font-bold tracking-tight">Textbook</h2>
            <p className="text-muted-foreground">Read chapters and review content.</p>
          </div>
        </div>
        <EmptyState title="No user found" description="Create a student user to read textbooks." icon={Inbox} />
      </div>
    )
  }

  const { id } = await params

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

  if (!textbook) notFound()

  return (
    <div className="flex h-[calc(100vh-4rem)] flex-col overflow-hidden bg-muted/5">
      <div className="flex items-center justify-between border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60 py-3 px-6 shrink-0 z-10">
        <div className="flex items-center gap-3 min-w-0">
          <h1 className="text-lg font-bold tracking-tight truncate">{textbook.title}</h1>
          <div className="flex items-center gap-2 text-sm text-muted-foreground">
             <span className="hidden sm:inline-block w-px h-4 bg-border" />
             <Badge variant="outline" className="font-normal text-xs">{textbook.subject}</Badge>
             {textbook.grade && (
               <Badge variant="secondary" className="font-normal text-xs">{textbook.grade}</Badge>
             )}
          </div>
        </div>
      </div>

      <div className="flex-1 overflow-hidden p-6">
        {chapters.length === 0 ? (
          <div className="h-full flex items-center justify-center rounded-lg border border-dashed bg-card">
            <EmptyState
              icon={BookOpen}
              title="No chapters"
              description="This textbook has no chapters yet."
              className="border-none shadow-none"
            />
          </div>
        ) : (
          <div className="h-full min-h-0 max-w-[1600px] mx-auto w-full">
            <TextbookReader chapters={chapters} knowledgePoints={knowledgePoints} />
          </div>
        )}
      </div>
    </div>
  )
}
