import { MarkdownRenderer } from "@/components/blog/MarkdownRenderer";
import { formatDate } from "@/lib/utils";
import { notFound } from "next/navigation";
import { getPostBySlug, getAllPosts } from "@/lib/posts";
import Image from "next/image";
import { Metadata } from "next";
import { BlogPostStructuredData } from "@/components/blog/BlogPostStructuredData";

interface BlogPostPageProps {
    params: Promise<{
        slug: string;
    }>;
}

// Generate static paths for all published posts
export async function generateStaticParams() {
    const posts = getAllPosts();
    return posts.map((post) => ({
        slug: post.slug,
    }));
}

// Generate dynamic metadata for SEO
export async function generateMetadata({ params }: BlogPostPageProps): Promise<Metadata> {
    const { slug } = await params;
    const post = getPostBySlug(slug);

    if (!post) {
        return {
            title: 'Post Not Found',
            description: 'The requested blog post could not be found.',
        };
    }

    const ogImage = post.ogImage || `https://source.unsplash.com/1200x630?education,${post.tags[0] || 'blog'}`;

    return {
        title: `${post.title} | Prejee Labs`,
        description: post.excerpt || post.metaDescription || `Read about ${post.title} and more insights on our blog.`,
        keywords: post.tags.join(', '),
        authors: [{ name: post.author }],
        openGraph: {
            title: post.title,
            description: post.excerpt || post.metaDescription || `Read about ${post.title} and more insights on our blog.`,
            type: 'article',
            publishedTime: new Date(post.publishedAt).toISOString(),
            authors: [post.author],
            images: [
                {
                    url: ogImage,
                    width: 1200,
                    height: 630,
                    alt: post.title,
                },
            ],
            siteName: 'Prejee',
        },
        twitter: {
            card: 'summary_large_image',
            title: post.title,
            description: post.excerpt || post.metaDescription || `Read about ${post.title} and more insights on our blog.`,
            images: [ogImage],
        },
        alternates: {
            canonical: `/labs/${post.slug}`,
        },
    };
}

export default async function BlogPostPage({ params }: BlogPostPageProps) {
    const { slug } = await params;
    const post = getPostBySlug(slug);

    if (!post) {
        notFound();
    }

    // Generate a gradient placeholder for the post image
    const placeholderImage = `data:image/svg+xml;base64,${Buffer.from(
        '<svg xmlns="http://www.w3.org/2000/svg" width="400" height="300" viewBox="0 0 400 300"><rect width="400" height="300" fill="#667eea"/><rect width="400" height="300" fill="url(#gradient)"/><defs><linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="100%"><stop offset="0%" stop-color="#667eea"/><stop offset="100%" stop-color="#764ba2"/></linearGradient></defs></svg>'
    ).toString('base64')}`;

    return (
        <>
            <BlogPostStructuredData post={post} />
            <section className="py-20 z-5 lg:mx-12 mx-2">
                <div className="max-w-3xl px-6 lg:px-8 mx-auto">
                    <article>
                        <header className="mb-5">
                            {post.ogImage && (
                                <div className="mb-8 md:mb-8 rounded-lg overflow-hidden aspect-video relative max-w-3xl mx-auto">
                                    <Image
                                        src={post.ogImage || placeholderImage}
                                        alt={post.title}
                                        fill
                                        className="object-cover"
                                        priority
                                    />
                                </div>
                            )}
                            <h1 className="text-4xl font-bold mt-2 md:mt-0 mb-4 text-left">{post.title}</h1>
                            <div className="flex items-center gap-4 text-gray-700 mb-4">
                                <span>{post.author} — {formatDate(post.publishedAt)}</span>
                            </div>
                            {post.excerpt && (
                                <p className="text-lg text-muted-foreground max-w-2xl mx-0">
                                    {post.excerpt}
                                </p>
                            )}
                        </header>
                        <div className="prose mx-auto prose-lg dark:prose-invert max-w-3xl">
                            <MarkdownRenderer content={post.content || ""} />
                        </div>
                    </article>
                </div>
            </section>
        </>
    );
}
