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

import { getTextbooks } from "@/modules/textbooks/data-access"
import { TextbookCard } from "@/modules/textbooks/components/textbook-card"
import { TextbookFilters } from "@/modules/textbooks/components/textbook-filters"
import { getCurrentStudentUser } from "@/modules/users/data-access"
import { EmptyState } from "@/shared/components/ui/empty-state"

export const dynamic = "force-dynamic"

type SearchParams = { [key: string]: string | string[] | undefined }

const getParam = (params: SearchParams, key: string) => {
  const v = params[key]
  return Array.isArray(v) ? v[0] : v
}

export default async function StudentTextbooksPage({
  searchParams,
}: {
  searchParams: Promise<SearchParams>
}) {
  const [student, sp] = await Promise.all([getCurrentStudentUser(), searchParams])

  if (!student) {
    return (
      <div className="h-full flex-1 flex-col space-y-8 p-8 md:flex">
        <EmptyState title="No user found" description="Create a student user to see textbooks." icon={UserX} />
      </div>
    )
  }

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

  const textbooks = await getTextbooks(q, subject, grade)
  const hasFilters = Boolean(q || (subject && subject !== "all") || (grade && grade !== "all"))

  return (
    <div className="h-full flex-1 flex-col space-y-8 p-8 md:flex">
      <div>
        <h2 className="text-2xl font-bold tracking-tight">Textbooks</h2>
        <p className="text-muted-foreground">Browse your course textbooks.</p>
      </div>

      <TextbookFilters />

      {textbooks.length === 0 ? (
        <EmptyState
          icon={BookOpen}
          title={hasFilters ? "No textbooks match your filters" : "No textbooks yet"}
          description={hasFilters ? "Try clearing filters or adjusting keywords." : "No textbooks are available right now."}
          action={hasFilters ? { label: "Clear filters", href: "/student/learning/textbooks" } : undefined}
          className="bg-card"
        />
      ) : (
        <div className="grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
          {textbooks.map((textbook) => (
            <TextbookCard key={textbook.id} textbook={textbook} hrefBase="/student/learning/textbooks" hideActions />
          ))}
        </div>
      )}
    </div>
  )
}

