import { Metadata } from 'next';
import { notFound } from 'next/navigation';
import Link from 'next/link';
import Image from 'next/image';
import { blogPosts, getBlogPostBySlug, BlogPost } from '@/data';

interface BlogPostPageProps {
  params: Promise<{ slug: string }>;
}

export async function generateStaticParams() {
  return blogPosts.map((post) => ({
    slug: post.slug,
  }));
}

export async function generateMetadata({ params }: BlogPostPageProps): Promise<Metadata> {
  const { slug } = await params;
  const post = getBlogPostBySlug(slug);

  if (!post) {
    return {
      title: 'Post Not Found',
    };
  }

  return {
    title: `${post.title} | Katheryn Trenshaw`,
    description: post.excerpt,
    openGraph: {
      title: post.title,
      description: post.excerpt,
      images: post.featuredImage ? [post.featuredImage] : [],
    },
  };
}

function formatDate(dateString: string): string {
  const date = new Date(dateString);
  return date.toLocaleDateString('en-GB', {
    day: 'numeric',
    month: 'long',
    year: 'numeric',
  });
}

function getAdjacentPosts(currentSlug: string): { prev: BlogPost | null; next: BlogPost | null } {
  const currentIndex = blogPosts.findIndex((p) => p.slug === currentSlug);
  return {
    prev: currentIndex > 0 ? blogPosts[currentIndex - 1] : null,
    next: currentIndex < blogPosts.length - 1 ? blogPosts[currentIndex + 1] : null,
  };
}

export default async function BlogPostPage({ params }: BlogPostPageProps) {
  const { slug } = await params;
  const post = getBlogPostBySlug(slug);

  if (!post) {
    notFound();
  }

  const { prev, next } = getAdjacentPosts(slug);

  return (
    <div className="min-h-screen bg-white pt-24">
      {/* Header */}
      <header className="mx-auto max-w-3xl px-4 py-12">
        <Link
          href="/blog"
          className="inline-flex items-center text-sm text-gray-500 hover:text-[#222] transition-colors mb-8"
        >
          <svg className="w-4 h-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M15 19l-7-7 7-7" />
          </svg>
          Back to Blog
        </Link>

        <time className="text-xs uppercase tracking-wider text-gray-500">
          {formatDate(post.postDate)}
        </time>

        <h1 className="mt-4 font-serif text-3xl md:text-4xl lg:text-5xl text-[#222] leading-tight">
          {post.title}
        </h1>
      </header>

      {/* Featured Image */}
      {post.featuredImage && (
        <div className="mx-auto max-w-5xl px-4 mb-12">
          <div className="relative aspect-[16/9] bg-gray-100 overflow-hidden">
            <Image
              src={post.featuredImage}
              alt={post.title}
              fill
              className="object-cover"
              sizes="(max-width: 1024px) 100vw, 1024px"
              priority
            />
          </div>
        </div>
      )}

      {/* Content */}
      <article className="mx-auto max-w-3xl px-4 pb-16">
        <div
          className="prose prose-lg max-w-none
            prose-headings:font-serif prose-headings:text-[#222]
            prose-p:text-gray-700 prose-p:leading-relaxed
            prose-a:text-[#222] prose-a:underline-offset-4
            prose-blockquote:border-l-4 prose-blockquote:border-gray-300 prose-blockquote:pl-6 prose-blockquote:italic prose-blockquote:text-gray-600
            prose-img:rounded-lg prose-img:mx-auto
            prose-figure:my-8
            prose-figcaption:text-center prose-figcaption:text-sm prose-figcaption:text-gray-500
            [&_figure]:my-8
            [&_.source]:text-sm [&_.source]:text-gray-500 [&_.source]:not-italic [&_.source]:mt-2"
          dangerouslySetInnerHTML={{ __html: post.content }}
        />
      </article>

      {/* Share & Navigation */}
      <div className="border-t border-gray-200">
        <div className="mx-auto max-w-3xl px-4 py-12">
          {/* Share Links */}
          <div className="flex items-center justify-center gap-4 mb-12">
            <span className="text-sm text-gray-500">Share:</span>
            <a
              href={`https://twitter.com/intent/tweet?text=${encodeURIComponent(post.title)}&url=${encodeURIComponent(`https://katheryntrenshaw.com/blog/${post.slug}`)}`}
              target="_blank"
              rel="noopener noreferrer"
              className="w-10 h-10 border border-gray-300 rounded-full flex items-center justify-center hover:border-[#222] transition-colors"
              aria-label="Share on Twitter"
            >
              <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
                <path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z" />
              </svg>
            </a>
            <a
              href={`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(`https://katheryntrenshaw.com/blog/${post.slug}`)}`}
              target="_blank"
              rel="noopener noreferrer"
              className="w-10 h-10 border border-gray-300 rounded-full flex items-center justify-center hover:border-[#222] transition-colors"
              aria-label="Share on Facebook"
            >
              <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 24 24">
                <path d="M22 12c0-5.523-4.477-10-10-10S2 6.477 2 12c0 4.991 3.657 9.128 8.438 9.878v-6.987h-2.54V12h2.54V9.797c0-2.506 1.492-3.89 3.777-3.89 1.094 0 2.238.195 2.238.195v2.46h-1.26c-1.243 0-1.63.771-1.63 1.562V12h2.773l-.443 2.89h-2.33v6.988C18.343 21.128 22 16.991 22 12z" />
              </svg>
            </a>
            <a
              href={`mailto:?subject=${encodeURIComponent(post.title)}&body=${encodeURIComponent(`Check out this article: https://katheryntrenshaw.com/blog/${post.slug}`)}`}
              className="w-10 h-10 border border-gray-300 rounded-full flex items-center justify-center hover:border-[#222] transition-colors"
              aria-label="Share via Email"
            >
              <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={1.5} d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
              </svg>
            </a>
          </div>

          {/* Previous / Next Navigation */}
          <div className="grid grid-cols-2 gap-8">
            {prev ? (
              <Link href={`/blog/${prev.slug}`} className="group">
                <span className="text-xs uppercase tracking-wider text-gray-500">Previous</span>
                <p className="mt-2 font-serif text-lg text-[#222] group-hover:text-gray-600 transition-colors line-clamp-2">
                  {prev.title}
                </p>
              </Link>
            ) : (
              <div />
            )}
            {next ? (
              <Link href={`/blog/${next.slug}`} className="group text-right">
                <span className="text-xs uppercase tracking-wider text-gray-500">Next</span>
                <p className="mt-2 font-serif text-lg text-[#222] group-hover:text-gray-600 transition-colors line-clamp-2">
                  {next.title}
                </p>
              </Link>
            ) : (
              <div />
            )}
          </div>
        </div>
      </div>

      {/* Related Posts */}
      <section className="bg-gray-50 py-16">
        <div className="mx-auto max-w-7xl px-4">
          <h2 className="text-center font-serif text-2xl text-[#222] mb-12">More Articles</h2>
          <div className="grid gap-8 md:grid-cols-3">
            {blogPosts
              .filter((p) => p.slug !== slug)
              .slice(0, 3)
              .map((relatedPost) => (
                <article key={relatedPost.id} className="group">
                  <Link href={`/blog/${relatedPost.slug}`}>
                    {relatedPost.featuredImage && (
                      <div className="relative aspect-[16/9] mb-4 overflow-hidden bg-gray-100">
                        <Image
                          src={relatedPost.featuredImage}
                          alt={relatedPost.title}
                          fill
                          className="object-cover transition-transform duration-500 group-hover:scale-105"
                          sizes="(max-width: 768px) 100vw, 33vw"
                        />
                      </div>
                    )}
                    <time className="text-xs uppercase tracking-wider text-gray-500">
                      {formatDate(relatedPost.postDate)}
                    </time>
                    <h3 className="mt-2 font-serif text-lg text-[#222] group-hover:text-gray-600 transition-colors">
                      {relatedPost.title}
                    </h3>
                  </Link>
                </article>
              ))}
          </div>
        </div>
      </section>
    </div>
  );
}
