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

type Args = {
  params: Promise<{ parentSlug: string }>
}

export default async function Page({ params: paramsPromise }: Args) {
  const { parentSlug } = await paramsPromise
  const payload = await getPayload({ config: configPromise })

  const parentResult = await payload.find({
    collection: 'categories',
    where: { slug: { equals: parentSlug }, parent: { exists: false } },
    limit: 1,
    depth: 1,
  })
  const parent = parentResult.docs[0]
  if (!parent) return notFound()

  const children = await payload.find({
    collection: 'categories',
    where: { parent: { equals: parent.id } },
    sort: 'order',
    limit: 100,
    depth: 1,
  })

  const childIds = children.docs.map((c) => c.id)
  const storiesResult = await (payload as any).find({
    collection: 'stories',
    where: { category: { in: [parent.id, ...childIds] } },
    sort: '-publishedAt',
    limit: 20,
    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 },
        ]}
      />

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

      {children.docs.length > 0 && (
        <section className="mb-12">
          <h2 className="text-xl font-semibold mb-4">Phân loại</h2>
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
            {children.docs.map((child) => (
              <CategoryCard
                key={String(child.id)}
                category={child as any}
                href={`/the-loai/${parentSlug}/${child.slug}`}
              />
            ))}
          </div>
        </section>
      )}

      {storiesResult.docs.length > 0 && (
        <section>
          <h2 className="text-xl font-semibold mb-4">Truyện trong thể loại</h2>
          <StoryGrid stories={storiesResult.docs} />
        </section>
      )}
    </div>
  )
}

export async function generateMetadata({ params: paramsPromise }: Args): Promise<Metadata> {
  const { parentSlug } = await paramsPromise
  const payload = await getPayload({ config: configPromise })
  const result = await payload.find({
    collection: 'categories',
    where: { slug: { equals: parentSlug }, parent: { exists: false } },
    limit: 1,
  })
  const cat = result.docs[0]
  return { title: cat ? `${cat.title} | Thể Loại` : 'Thể Loại' }
}

export async function generateStaticParams() {
  try {
    const payload = await getPayload({ config: configPromise })
    const categories = await payload.find({
      collection: 'categories',
      where: { parent: { exists: false } },
      limit: 1000,
      select: { slug: true },
    })
    return categories.docs.map(({ slug }) => ({ parentSlug: slug }))
  } catch {
    return []
  }
}
