import { Book } from '@/payload-types'
import { getPayload, PaginatedDocs } from 'payload'
import configPromise from '@payload-config'
import BooksPageClient from './page.client'
import { PageBreadCrumb, Route } from '@/components/PageBreadCrumb'

  const breadcrumRoutes: Route[] = [
    {
      label: 'Home',
      href: '/',
    },
    {
      label: 'Search',
      href: '/search',
    },
  ]

type Params = Promise<{ slug: string }>
type SearchParams = Promise<{ [key: string]: string | undefined }>

type Props = {
  params: Params
  searchParams: SearchParams
}
const BooksPage = async (props: Props) => {
  const searchParams = await props.searchParams

  const defaultLimit = 25
  const defaultPage = 1

  const pageFromUrl = parseInt(searchParams?.page || '', 10)
  const limitFromUrl = parseInt(searchParams?.limit || '', 10)

  const payload = await getPayload({ config: configPromise })

  const initialBooks = (await payload.find({
    collection: 'books',
    depth: 2,
    page: !Number.isNaN(pageFromUrl) ? pageFromUrl : defaultPage,
    limit: !Number.isNaN(limitFromUrl) ? limitFromUrl : defaultLimit,
    overrideAccess: false,
    select: {
      title: true,
      authors: true,
      publication: true,
      lcc: true,
      genre: true,
      isbn: true,
      copies: true,
    },
  })) as PaginatedDocs<Book>

  return (
    <>
      <PageBreadCrumb routes={breadcrumRoutes} />
      <BooksPageClient initialBooks={initialBooks} />
    </>
  )
}

export default BooksPage
