import { getAllTags } from '@/lib/tags'
import { getAllPostsMeta } from '@/lib/posts'
import { slugify } from '@/utils/slug'
import type { Metadata } from 'next'
import Link from 'next/link'
import { metadata } from '@/app/metadata'
import { dateFormatter } from '@/utils/time'

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

export async function generateMetadata(): Promise<Metadata> {
  return {
    title: `Tags | ${metadata.title!.toString()}`,
    description: 'List of tags',
    openGraph: {
      type: 'website',
      title: `Tags | ${metadata.title!.toString()}`,
      description: 'List of tags',
      url: process.env.SITE_URL + '/tags',
      siteName: metadata.title!.toString(),
    },
  }
}

export default function TagsPage() {
  const tags = getAllTags()
  const posts = getAllPostsMeta()
  const tagNames = Object.keys(tags).toSorted((a, b) => a.localeCompare(b))

  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</div>

      <ul className="border-l border-border ml-1">
        {tagNames.map((tag) => {
          const tagPosts = posts.filter((post) => post.tags && post.tags.includes(tag))

          return (
            <li key={tag} className="pl-5">
              <Link
                href={`/tags/${slugify(tag)}`}
                className="group flex items-baseline gap-2 py-2 px-2 -ml-2 hover:bg-accent/10 transition-colors"
              >
                <span className="font-bold group-hover:text-accent transition-colors capitalize">
                  {tag}
                </span>
                <span className="text-xs text-fg">({tagPosts.length})</span>
              </Link>

              <ul className="border-l border-border ml-3 mb-3">
                {tagPosts.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>
            </li>
          )
        })}
      </ul>
    </main>
  )
}
