import { Metadata } from 'next'
import { notFound } from 'next/navigation'
import Link from 'next/link'
import { getAllPosts, getPostBySlug, getRelatedPosts } from '@/lib/markdown'
import { formatDate, formatRelativeDate } from '@/lib/utils'
import { TableOfContents } from '@/components/blog/table-of-contents'
import { ReadingProgress } from '@/components/blog/reading-progress'
import { StickyFooter } from '@/components/blog/sticky-footer'
import MarkdownRenderer from '@/components/blog/markdown-renderer'

export async function generateStaticParams() {
  const posts = await getAllPosts()
  return posts.map(post => ({ slug: post.slug.split('/') }))
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string[] }>
}): Promise<Metadata> {
  const { slug } = await params
  const slugPath = slug.join('/')
  const post = await getPostBySlug(slugPath)

  if (!post) {
    return { title: 'Articol negăsit' }
  }

  return {
    title: post.frontmatter.title,
    description: post.frontmatter.description,
    authors: [{ name: post.frontmatter.author }],
    openGraph: {
      title: post.frontmatter.title,
      description: post.frontmatter.description,
      type: 'article',
      publishedTime: post.frontmatter.date,
      authors: [post.frontmatter.author],
      images: post.frontmatter.image ? [post.frontmatter.image] : [],
    },
    twitter: {
      card: 'summary_large_image',
      title: post.frontmatter.title,
      description: post.frontmatter.description,
      images: post.frontmatter.image ? [post.frontmatter.image] : [],
    },
  }
}

function extractHeadings(content: string) {
  const headingRegex = /^(#{2,3})\s+(.+)$/gm
  const headings: { id: string; text: string; level: number }[] = []
  let match

  while ((match = headingRegex.exec(content)) !== null) {
    const level = match[1].length
    const text = match[2]
    const id = text
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, '-')
      .replace(/(^-|-$)/g, '')
    headings.push({ id, text, level })
  }

  return headings
}

export default async function BlogPostPage({ params }: { params: Promise<{ slug: string[] }> }) {
  const { slug } = await params
  const slugPath = slug.join('/')
  const post = await getPostBySlug(slugPath)

  if (!post) {
    notFound()
  }

  const relatedPosts = await getRelatedPosts(slugPath)
  const headings = extractHeadings(post.content)
  const fullUrl = `${process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3030'}/blog/${slugPath}`

  return (
    <>
      <ReadingProgress />

      <div className="max-w-7xl mx-auto px-6 py-16">
        <div className="flex gap-12">
          <TableOfContents headings={headings} />

          <article className="flex-1 min-w-0">
            <header className="mb-16 border border-[var(--neon-cyan)] bg-[rgb(var(--bg-primary))] p-8 relative">
              <div className="border-b border-[var(--neon-pink)] pb-4 mb-6 relative">
                <div className="flex items-center gap-3 mb-3 justify-end">
                  <p className="font-mono text-xs text-[var(--neon-cyan)] uppercase tracking-widest">
                    &gt;&gt; CLASSIFIED_DOC://PUBLIC_ACCESS
                  </p>
                  <div className="flex gap-1.5">
                    <div className="w-4 h-4 border border-[rgb(var(--border-primary))] hover:bg-red-500/10 cursor-pointer" />
                    <div className="w-4 h-4 border border-[rgb(var(--border-primary))] hover:bg-yellow-500/10 cursor-pointer" />
                    <div className="w-4 h-4 border border-[rgb(var(--border-primary))] hover:bg-green-500/10 cursor-pointer" />
                  </div>
                </div>
                <div className="flex flex-wrap gap-2 mb-2">
                  {post.frontmatter.tags.map((tag: string) => (
                    <Link
                      key={tag}
                      href={`/tags/${tag}`}
                      className="px-3 py-1 bg-cyan-500/5 border border-[var(--neon-cyan)] text-cyan-400 text-xs font-mono uppercase shadow-[0_0_8px_rgba(90,139,149,0.3)] hover:shadow-[0_0_12px_rgba(90,139,149,0.5)] transition-all"
                    >
                      #{tag}
                    </Link>
                  ))}
                </div>
              </div>

              <div className="border-l border-[var(--neon-magenta)] pl-6 relative">
                <h1 className="text-4xl md:text-5xl font-mono font-bold text-[var(--neon-cyan)] uppercase tracking-tight leading-tight mb-6">
                  {post.frontmatter.title}
                </h1>

                <p className="text-lg text-[rgb(var(--text-secondary))] leading-relaxed mb-6 font-mono">
                  <span className="text-[var(--neon-pink)]">&gt;&gt;</span>{' '}
                  {post.frontmatter.description}
                </p>
              </div>

              <div className="flex items-center gap-4 pt-6 border-t border-[var(--neon-purple)] relative">
                <div className="w-12 h-12 border border-[var(--neon-cyan)] bg-[rgb(var(--bg-secondary))] flex items-center justify-center">
                  <span className="font-mono text-[var(--neon-cyan)] text-xs">
                    {post.frontmatter.author.charAt(0).toUpperCase()}
                  </span>
                </div>
                <div>
                  <p className="font-mono font-bold text-[var(--neon-cyan)] uppercase text-sm">
                    {post.frontmatter.author}
                  </p>
                  <div className="flex items-center gap-2 text-xs text-[rgb(var(--text-muted))] font-mono">
                    <time className="text-[var(--neon-magenta)]">
                      {formatDate(post.frontmatter.date)}
                    </time>
                    <span className="text-[var(--neon-pink)]">//</span>
                    <span className="text-[var(--neon-cyan)]">{post.readingTime}min READ</span>
                  </div>
                </div>
              </div>
            </header>

            {post.frontmatter.image && (
              <div className="relative aspect-video mb-16 border border-[var(--neon-pink)] overflow-hidden">
                <img
                  src={post.frontmatter.image}
                  alt={post.frontmatter.title}
                  className="w-full h-full object-cover"
                />
              </div>
            )}

            <div className="prose prose-invert prose-lg max-w-none cyberpunk-prose">
              <MarkdownRenderer content={post.content} />
            </div>

            {relatedPosts.length > 0 && (
              <section className="mt-12 pt-8 border-t border-zinc-800">
                <h2 className="text-2xl font-mono font-bold uppercase text-[var(--neon-cyan)] mb-6">
                  // Articole similare
                </h2>
                <div className="grid gap-6 md:grid-cols-3">
                  {relatedPosts.map(relatedPost => (
                    <Link
                      key={relatedPost.slug}
                      href={`/blog/${relatedPost.slug}`}
                      className="block p-4 border border-zinc-800 bg-zinc-950 hover:border-[var(--neon-cyan)] transition-all hover:shadow-[0_0_8px_rgba(90,139,149,0.2)]"
                    >
                      <h3 className="font-mono font-semibold text-cyan-400 mb-2 line-clamp-2">
                        {relatedPost.frontmatter.title}
                      </h3>
                      <p className="text-sm text-zinc-400 line-clamp-2">
                        {relatedPost.frontmatter.description}
                      </p>
                      <p className="text-xs text-zinc-600 mt-2 font-mono">
                        {formatDate(relatedPost.frontmatter.date)}
                      </p>
                    </Link>
                  ))}
                </div>
              </section>
            )}

            <nav className="flex justify-between items-center mt-12 pt-8 border-t border-zinc-800">
              <Link
                href="/blog"
                className="flex items-center text-[var(--neon-pink)] hover:text-[var(--neon-magenta)] transition-all font-mono text-sm uppercase border border-[var(--neon-pink)] px-4 py-2 hover:shadow-[0_0_6px_rgba(155,90,110,0.3)]"
              >
                <svg className="mr-2 w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path
                    strokeLinecap="round"
                    strokeLinejoin="round"
                    strokeWidth={2}
                    d="M15 19l-7-7 7-7"
                  />
                </svg>
                [BACK TO BLOG]
              </Link>
            </nav>
          </article>
        </div>
      </div>

      <StickyFooter url={fullUrl} title={post.frontmatter.title} />
    </>
  )
}
