import type { JSX } from "react"
import { Suspense } from "react"
import { BookOpen } from "lucide-react"
import { TextbookCard } from "@/modules/textbooks/components/textbook-card"
import { TextbookFormDialog } from "@/modules/textbooks/components/textbook-form-dialog"
import { getTextbooks } from "@/modules/textbooks/data-access"
import { TextbookFilters } from "@/modules/textbooks/components/textbook-filters"
import { EmptyState } from "@/shared/components/ui/empty-state"
import { getParam, type SearchParams } from "@/shared/lib/search-params"

export const dynamic = "force-dynamic"

async function TextbooksResults({ searchParams }: { searchParams: Promise<SearchParams> }): Promise<JSX.Element> {
  const params = await searchParams

  const q = getParam(params, "q") || undefined
  const subject = getParam(params, "subject")
  const grade = getParam(params, "grade")

  const textbooks = await getTextbooks(q, subject || undefined, grade || undefined)

  const hasFilters = Boolean(q || (subject && subject !== "all") || (grade && grade !== "all"))

  if (textbooks.length === 0) {
    return (
      <EmptyState
        icon={BookOpen}
        title={hasFilters ? "No textbooks match your filters" : "No textbooks yet"}
        description={hasFilters ? "Try clearing filters or adjusting keywords." : "Create your first textbook to start organizing chapters."}
        action={hasFilters ? { label: "Clear filters", href: "/teacher/textbooks" } : undefined}
        className="min-h-[400px] border-muted-foreground/10"
      />
    )
  }

  return (
    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
      {textbooks.map((textbook) => (
        <TextbookCard key={textbook.id} textbook={textbook} />
      ))}
    </div>
  )
}

export default async function TextbooksPage({ searchParams }: { searchParams: Promise<SearchParams> }): Promise<JSX.Element> {
  return (
    <div className="space-y-6 p-8">
      {/* Page Header */}
      <div className="flex flex-col gap-4 md:flex-row md:items-center md:justify-between">
        <div>
          <h1 className="text-2xl font-bold tracking-tight">Textbooks</h1>
          <p className="text-muted-foreground">
            Manage your digital curriculum resources and chapters.
          </p>
        </div>
        <TextbookFormDialog />
      </div>

      <Suspense fallback={<div className="h-14 w-full animate-pulse rounded-lg bg-muted" />}>
        <TextbookFilters />
      </Suspense>

      <Suspense fallback={<div className="h-[360px] w-full animate-pulse rounded-md bg-muted" />}>
        <TextbooksResults searchParams={searchParams} />
      </Suspense>
    </div>
  )
}
