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 { PaginationNav } from '@/components/PaginationNav'
import { StoryGrid } from '@/components/StoryGrid'

const LIMIT = 20

type Args = {
  params: Promise<{ parentSlug: string; childSlug: string }>
  searchParams: Promise<{ page?: string }>
}

export default async function Page({ params: paramsPromise, searchParams: searchParamsPromise }: Args) {
  const { parentSlug, childSlug } = 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 parentResult = await payload.find({
    collection: 'categories',
    where: { slug: { equals: parentSlug }, parent: { exists: false } },
    limit: 1,
  })
  const parent = parentResult.docs[0]
  if (!parent) return notFound()

  const childResult = await payload.find({
    collection: 'categories',
    where: { slug: { equals: childSlug }, parent: { equals: parent.id } },
    limit: 1,
    depth: 1,
  })
  const child = childResult.docs[0]
  if (!child) return notFound()

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

  return (
    <div className="container py-8">
      <Breadcrumb
        items={[
          { label: 'Trang chủ', href: '/' },
          { label: 'Thể Loại', href: '/the-loai' },
          { label: parent.title, href: `/the-loai/${parentSlug}` },
          { label: child.title },
        ]}
      />

      <h1 className="text-3xl font-bold mb-2">{child.title}</h1>
      {(child as any).description && (
        <p className="text-muted-foreground mb-8">{(child as any).description}</p>
      )}

      <StoryGrid stories={stories.docs} />

      <PaginationNav
        page={currentPage}
        totalPages={stories.totalPages ?? 1}
        basePath={`/the-loai/${parentSlug}/${childSlug}`}
      />
    </div>
  )
}

export async function generateMetadata({ params: paramsPromise }: Args): Promise<Metadata> {
  const { parentSlug, childSlug } = await paramsPromise
  const payload = await getPayload({ config: configPromise })

  const [parentResult, childResult] = await Promise.all([
    payload.find({ collection: 'categories', where: { slug: { equals: parentSlug } }, limit: 1 }),
    payload.find({ collection: 'categories', where: { slug: { equals: childSlug } }, limit: 1 }),
  ])

  const parent = parentResult.docs[0]
  const child = childResult.docs[0]
  return {
    title: child && parent ? `${child.title} - ${parent.title} | Thể Loại` : 'Thể Loại',
  }
}

export async function generateStaticParams() {
  try {
    const payload = await getPayload({ config: configPromise })
    const parents = await payload.find({
      collection: 'categories',
      where: { parent: { exists: false } },
      limit: 1000,
      select: { slug: true },
    })

    const params: { parentSlug: string; childSlug: string }[] = []
    for (const parent of parents.docs) {
      const children = await payload.find({
        collection: 'categories',
        where: { parent: { equals: parent.id } },
        limit: 1000,
        select: { slug: true },
      })
      for (const child of children.docs) {
        params.push({ parentSlug: parent.slug!, childSlug: child.slug! })
      }
    }
    return params
  } catch {
    return []
  }
}
