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<{ 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 tagResult = await (payload as any).find({
    collection: 'tags',
    where: { slug: { equals: slug } },
    limit: 1,
  })
  const tag = tagResult.docs[0]
  if (!tag) return notFound()

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

  return (
    <div className="container py-8">
      <Breadcrumb
        items={[
          { label: 'Trang chủ', href: '/' },
          { label: 'Tags', href: '/tags' },
          { label: tag.title },
        ]}
      />

      <h1 className="text-3xl font-bold mb-8"># {tag.title}</h1>

      <StoryGrid stories={stories.docs} />

      <PaginationNav
        page={currentPage}
        totalPages={stories.totalPages ?? 1}
        basePath={`/tags/${slug}`}
      />
    </div>
  )
}

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: 'tags',
    where: { slug: { equals: slug } },
    limit: 1,
  })
  const tag = result.docs[0]
  return { title: tag ? `#${tag.title} | Tags` : 'Tags' }
}

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