import type { Metadata } from 'next/types'

import configPromise from '@payload-config'
import { getPayload } from 'payload'
import { notFound } from 'next/navigation'
import React from 'react'

import { Breadcrumb } from '@/components/Breadcrumb'
import { ChapterList } from '@/components/ChapterList'
import { StoryHero } from '@/components/StoryHero'

const CHAPTERS_PER_PAGE = 50

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

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

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

  const storyResult = await (payload as any).find({
    collection: 'stories',
    where: { slug: { equals: slug } },
    limit: 1,
    depth: 2,
    draft: false,
    overrideAccess: false,
  })
  const story = storyResult.docs[0]
  if (!story) return notFound()

  const chaptersResult = await (payload as any).find({
    collection: 'chapters',
    where: { story: { equals: story.id } },
    sort: 'chapterNumber',
    limit: CHAPTERS_PER_PAGE,
    page: currentPage,
    depth: 0,
    draft: false,
    overrideAccess: false,
  })

  const firstChapter = chaptersResult.docs[0] ?? null

  const category = story.category && typeof story.category === 'object' ? story.category : null
  const parentBreadcrumb = category?.breadcrumbs?.[0] ?? null

  return (
    <>
      <div className="container pt-8 pb-0">
        <Breadcrumb
          items={[
            { label: 'Trang chủ', href: '/' },
            parentBreadcrumb?.url
              ? { label: parentBreadcrumb.label ?? 'Thể Loại', href: parentBreadcrumb.url }
              : { label: 'Thể Loại', href: '/the-loai' },
            { label: story.title },
          ]}
        />
      </div>

      <StoryHero
        story={story}
        firstChapterSlug={firstChapter?.slug ?? null}
        totalChapters={chaptersResult.totalDocs}
      />

      <div className="border-t border-border">
        <ChapterList
          storySlug={slug}
          chapters={chaptersResult.docs}
          totalDocs={chaptersResult.totalDocs}
          currentPage={currentPage}
          totalPages={chaptersResult.totalPages}
        />
      </div>
    </>
  )
}

export async function generateStaticParams() {
  try {
    const payload = await getPayload({ config: configPromise })
    const stories = await (payload as any).find({
      collection: 'stories',
      limit: 1000,
      draft: false,
      select: { slug: true },
      overrideAccess: false,
    })
    return stories.docs.map((s: any) => ({ slug: s.slug }))
  } catch {
    return []
  }
}

export async function generateMetadata({ params: paramsPromise }: Args): Promise<Metadata> {
  const { slug } = await paramsPromise
  const payload = await getPayload({ config: configPromise })
  const result = await (payload as any).find({
    collection: 'stories',
    where: { slug: { equals: slug } },
    limit: 1,
    depth: 0,
    draft: false,
  })
  const story = result.docs[0]
  return {
    title: story ? `${story.title} | Truyện Hay` : 'Truyện',
    description: story?.author ? `Tác giả: ${story.author}` : undefined,
  }
}

