import { metadata } from '@/app/metadata'
import { getAllTags, getPostsByTag, getTagBySlug } from '@/lib/tags'
import { dateFormatter } from '@/utils/time'
import type { Metadata } from 'next'
import Link from 'next/link'

type TagPageProps = {
  params: Promise<{
    tagSlug: string
  }>
}

export async function generateStaticParams() {
  const tags = getAllTags()
  return Object.keys(tags).map((tag) => ({
    tagSlug: tag,
  }))
}

export async function generateMetadata({ params }: TagPageProps): Promise<Metadata> {
  const { tagSlug } = await params
  const tag = getTagBySlug(tagSlug)

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

export default async function TagPage({ params }: TagPageProps) {
  const { tagSlug } = await params
  const posts = getPostsByTag(tagSlug)
  const tag = getTagBySlug(tagSlug)

  if (!tag) {
    return (
      <main className="max-w-3xl 2xl:max-w-4xl mx-auto px-4 py-8 lg:py-16 w-full">
        <h1>Tag not found</h1>
        <Link href="/tags">Back to tags</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">~/tags/{tagSlug}</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>
  )
}
