import type { Metadata } from 'next/types'

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

import { CategoryCard } from '@/components/CategoryCard'

export const revalidate = 600

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

  const categories = await payload.find({
    collection: 'categories',
    where: { parent: { exists: false } },
    sort: 'order',
    limit: 100,
    depth: 1,
  }).catch(() => ({ docs: [] }))

  return (
    <div className="container py-12">
      <h1 className="text-3xl font-bold mb-8">Thể Loại</h1>
      {categories.docs.length === 0 ? (
        <p className="text-muted-foreground">Chưa có thể loại nào.</p>
      ) : (
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-6">
          {categories.docs.map((cat) => (
            <CategoryCard
              key={String(cat.id)}
              category={cat as any}
              href={`/the-loai/${cat.slug}`}
            />
          ))}
        </div>
      )}
    </div>
  )
}

export function generateMetadata(): Metadata {
  return {
    title: 'Thể Loại Truyện',
    description: 'Danh sách tất cả thể loại truyện',
  }
}
