import type { Metadata } from 'next/types'

import configPromise from '@payload-config'
import { getPayload } from 'payload'
import React from 'react'

import { PaginationNav } from '@/components/PaginationNav'
import { StoryGrid } from '@/components/StoryGrid'

const LIMIT = 20

type Args = {
  searchParams: Promise<{ page?: string }>
}

export default async function Page({ searchParams: searchParamsPromise }: Args) {
  const { page: pageParam } = await searchParamsPromise
  const currentPage = Math.max(1, parseInt(pageParam ?? '1', 10))

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

  const stories = await (payload as any).find({
    collection: 'stories',
    sort: '-publishedAt',
    limit: LIMIT,
    page: currentPage,
    depth: 1,
    overrideAccess: false,
  })

  return (
    <div className="container py-8">
      <h1 className="text-3xl font-bold mb-8">Truyện Mới</h1>
      <StoryGrid stories={stories.docs} />
      <PaginationNav
        page={currentPage}
        totalPages={stories.totalPages ?? 1}
        basePath="/truyen-moi"
      />
    </div>
  )
}

export function generateMetadata(): Metadata {
  return {
    title: 'Truyện Mới | Truyện Hay',
    description: 'Danh sách truyện mới cập nhật',
  }
}
