import { metadata } from '@/app/metadata'
import { getAllCategories, getCategoryBySlug, getPostsByCategory } from '@/lib/categories'
import { dateFormatter } from '@/utils/time'
import type { Metadata } from 'next'
import Link from 'next/link'

type CategoryPageProps = {
  params: Promise<{
    categorySlug: string
  }>
}

export async function generateStaticParams() {
  const categories = getAllCategories()
  return Object.keys(categories).map((category) => ({
    categorySlug: category,
  }))
}

export async function generateMetadata({ params }: CategoryPageProps): Promise<Metadata> {
  const { categorySlug } = await params
  const category = getCategoryBySlug(categorySlug)

  return {
    title: `${category} | ${metadata.title!.toString()}`,
    description: 'List of posts in this category',
    openGraph: {
      type: 'website',
      title: `${category} | ${metadata.title!.toString()}`,
      description: 'List of posts in this category',
      url: process.env.SITE_URL + `/categories/${categorySlug}`,
      siteName: metadata.title!.toString(),
    },
  }
}

export default async function CategoryPage({ params }: CategoryPageProps) {
  const { categorySlug } = await params
  const posts = getPostsByCategory(categorySlug)
  const category = getCategoryBySlug(categorySlug)

  if (!category) {
    return (
      <main className="max-w-3xl 2xl:max-w-4xl mx-auto px-4 py-8 lg:py-16 w-full">
        <h1>Category not found</h1>
        <Link href="/categories">Back to categories</Link>
      </main>
    )
  }

  return (
    <main className="max-w-3xl 2xl:max-w-4xl mx-auto px-4 py-8 mb-8 lg:py-16 w-full">
      <div className="font-mono text-sm text-fg-dim mb-2">~/categories/{categorySlug}</div>

      <ul className="border-l border-border ml-1 mb-3">
        {posts.map((post) => (
          <li key={post.slug} className="pl-5">
            <Link
              href={`/posts/${post.slug}`}
              className="group flex items-baseline justify-between gap-3 py-1.5 px-2 -ml-2 border-l-2 border-transparent hover:bg-accent/10 hover:border-accent transition-colors"
            >
              <span className="group-hover:text-accent transition-colors truncate">
                {post.title}
              </span>
              {post.date && (
                <time
                  dateTime={new Date(post.date).toISOString()}
                  className="text-sm whitespace-nowrap"
                >
                  {dateFormatter.format(new Date(post.date))}
                </time>
              )}
            </Link>
          </li>
        ))}
      </ul>
    </main>
  )
}
