import { Metadata } from 'next'
import { notFound } from 'next/navigation'
import Link from 'next/link'
import { getAllTags, getPostsByTag, getTagInfo, getRelatedTags } from '@/lib/tags'
import { TagList } from '@/components/blog/tag-list'
import { formatDate } from '@/lib/utils'

export async function generateStaticParams() {
  const tags = await getAllTags()
  return tags.map(tag => ({ tag: tag.slug }))
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ tag: string }>
}): Promise<Metadata> {
  const { tag } = await params
  const tagInfo = await getTagInfo(tag)

  if (!tagInfo) {
    return { title: 'Tag negăsit' }
  }

  return {
    title: `Tag: ${tagInfo.name}`,
    description: `Articole marcate cu #${tagInfo.name}. ${tagInfo.count} articole disponibile.`,
    openGraph: {
      title: `Tag: ${tagInfo.name}`,
      description: `Explorează ${tagInfo.count} articole despre ${tagInfo.name}`,
    },
  }
}

function PostCard({ post }: { post: any }) {
  return (
    <article className="border-2 border-slate-700 bg-slate-900 p-6 hover:border-cyan-400 transition">
      {post.frontmatter.image && (
        <img
          src={post.frontmatter.image}
          alt={post.frontmatter.title}
          className="w-full h-48 object-cover mb-4 border-2 border-slate-800"
        />
      )}

      <div className="flex items-center gap-2 font-mono text-xs text-zinc-500 mb-3 uppercase">
        <time dateTime={post.frontmatter.date}>{formatDate(post.frontmatter.date)}</time>
        <span>&gt;</span>
        <span>{post.readingTime} min</span>
      </div>

      <h2 className="font-mono text-lg font-bold mb-3 uppercase">
        <Link href={`/blog/${post.slug}`} className="text-cyan-400 hover:text-cyan-300 transition">
          {post.frontmatter.title}
        </Link>
      </h2>

      <p className="text-zinc-400 mb-4 line-clamp-3">{post.frontmatter.description}</p>

      {post.frontmatter.tags && <TagList tags={post.frontmatter.tags} variant="minimal" />}
    </article>
  )
}

export default async function TagPage({ params }: { params: Promise<{ tag: string }> }) {
  const { tag } = await params
  const tagInfo = await getTagInfo(tag)

  if (!tagInfo) {
    notFound()
  }

  const posts = await getPostsByTag(tag)
  const relatedTags = await getRelatedTags(tag)

  return (
    <div className="min-h-screen bg-slate-950 text-slate-100">
      <div className="max-w-6xl mx-auto px-6 py-12">
        <div className="border-4 border-cyan-800 bg-cyan-950 p-8 mb-8">
          <div className="flex items-center justify-between flex-wrap gap-4">
            <div>
              <p className="font-mono text-xs text-cyan-600 uppercase tracking-widest mb-2">
                TAG ARCHIVE
              </p>
              <h1 className="font-mono text-3xl font-bold uppercase mb-2">
                <span className="text-cyan-400">#{tagInfo.name}</span>
              </h1>
              <p className="font-mono text-sm text-cyan-300">
                &gt; {tagInfo.count} {tagInfo.count === 1 ? 'DOCUMENT' : 'DOCUMENTS'}
              </p>
            </div>
            <div>
              <Link
                href="/tags"
                className="inline-flex items-center px-4 py-2 font-mono text-xs uppercase border-2 border-cyan-400 bg-slate-900 text-cyan-400 hover:bg-cyan-900 transition"
              >
                &gt; ALL TAGS
              </Link>
            </div>
          </div>
        </div>

        <div className="grid gap-8 lg:grid-cols-4">
          <div className="lg:col-span-3">
            {posts.length === 0 ? (
              <div className="border-4 border-slate-800 bg-slate-900 p-12 text-center">
                <p className="font-mono text-zinc-400 mb-6 uppercase">&gt; NO DOCUMENTS FOUND</p>
                <Link
                  href="/blog"
                  className="inline-block px-6 py-3 font-mono text-sm uppercase border-2 border-cyan-400 bg-cyan-900 text-cyan-100 hover:bg-cyan-800 transition"
                >
                  &gt; VIEW ALL POSTS
                </Link>
              </div>
            ) : (
              <div className="grid gap-6">
                {posts.map(post => (
                  <PostCard key={post.slug} post={post} />
                ))}
              </div>
            )}
          </div>

          <aside className="lg:col-span-1 space-y-6">
            {relatedTags.length > 0 && (
              <div className="border-2 border-slate-700 bg-slate-900 p-6">
                <div className="border-b-2 border-slate-700 pb-3 mb-4">
                  <h2 className="font-mono text-sm font-bold uppercase text-cyan-400">
                    RELATED TAGS
                  </h2>
                </div>
                <div className="space-y-2">
                  {relatedTags.map(tag => (
                    <Link
                      key={tag.slug}
                      href={`/tags/${tag.slug}`}
                      className="flex items-center justify-between p-2 border border-slate-700 hover:border-cyan-400 hover:bg-slate-800 transition"
                    >
                      <span className="font-mono text-xs uppercase text-zinc-300">#{tag.name}</span>
                      <span className="font-mono text-xs text-zinc-500">[{tag.count}]</span>
                    </Link>
                  ))}
                </div>
              </div>
            )}

            <div className="border-2 border-slate-700 bg-slate-900 p-6">
              <div className="border-b-2 border-slate-700 pb-3 mb-4">
                <h2 className="font-mono text-sm font-bold uppercase text-cyan-400">QUICK NAV</h2>
              </div>
              <div className="space-y-2">
                <Link
                  href="/blog"
                  className="block p-2 border border-slate-700 hover:border-cyan-400 hover:bg-slate-800 transition font-mono text-xs uppercase"
                >
                  &gt; ALL POSTS
                </Link>
                <Link
                  href="/tags"
                  className="block p-2 border border-slate-700 hover:border-cyan-400 hover:bg-slate-800 transition font-mono text-xs uppercase"
                >
                  &gt; ALL TAGS
                </Link>
                <Link
                  href="/"
                  className="block p-2 border border-slate-700 hover:border-cyan-400 hover:bg-slate-800 transition font-mono text-xs uppercase"
                >
                  &gt; HOME
                </Link>
              </div>
            </div>
          </aside>
        </div>
      </div>
    </div>
  )
}
