"use client";

import { useEffect, useState } from "react";
import ReactLenis from "lenis/react";
import BlogCardEleven from '@/components/sections/blog/BlogCardEleven';
import NavbarStyleApple from '@/components/navbar/NavbarStyleApple/NavbarStyleApple';
import FooterBaseReveal from '@/components/sections/footer/FooterBaseReveal';
import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";

type BlogPost = {
    id: string;
    title: string;
    author: string;
    description: string;
    tags: string[];
    imageSrc?: string;
    imageAlt?: string;
    videoSrc?: string;
    videoAriaLabel?: string;
    onBlogClick?: () => void;
};

type BlogCard = {
    id: string;
    title: string;
    author: string;
    description: string;
    tags: string[];
    onBlogClick?: () => void;
} & (
    | { imageSrc: string; imageAlt?: string; videoSrc?: never; videoAriaLabel?: never }
    | { videoSrc: string; videoAriaLabel?: string; imageSrc?: never; imageAlt?: never }
);

const defaultPosts: BlogPost[] = [
    {
        id: "1",        title: "The Art of Coffee Brewing",        author: "Sarah Johnson",        description: "Discover the secrets behind the perfect cup of coffee with our comprehensive brewing guide.",        tags: ["Coffee", "Brewing", "Guide"],
        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Coffee brewing process",        onBlogClick: () => console.log("Blog 1 clicked"),
    },
    {
        id: "2",        title: "Bean Selection Mastery",        author: "Mike Davis",        description: "Learn how to select the perfect coffee beans for your taste preferences and brewing methods.",        tags: ["Beans", "Selection", "Quality"],
        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Coffee bean selection",        onBlogClick: () => console.log("Blog 2 clicked"),
    },
    {
        id: "3",        title: "Café Culture Around the World",        author: "Emma Thompson",        description: "Explore how different cultures celebrate coffee and what makes each region's café culture unique.",        tags: ["Culture", "Travel", "Coffee"],
        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Global café culture",        onBlogClick: () => console.log("Blog 3 clicked"),
    },
    {
        id: "4",        title: "Sustainable Coffee Practices",        author: "Alex Rivera",        description: "Understanding the importance of sustainable coffee farming and how it benefits both farmers and consumers.",        tags: ["Sustainability", "Farming", "Ethics"],
        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Sustainable coffee farming",        onBlogClick: () => console.log("Blog 4 clicked"),
    },
];

function convertToBlogCard(post: BlogPost): BlogCard {
    // Ensure we have either imageSrc or videoSrc, prioritizing imageSrc
    if (post.imageSrc) {
        return {
            id: post.id,
            title: post.title,
            author: post.author,
            description: post.description,
            tags: post.tags,
            imageSrc: post.imageSrc,
            imageAlt: post.imageAlt,
            onBlogClick: post.onBlogClick
        };
    } else if (post.videoSrc) {
        return {
            id: post.id,
            title: post.title,
            author: post.author,
            description: post.description,
            tags: post.tags,
            videoSrc: post.videoSrc,
            videoAriaLabel: post.videoAriaLabel,
            onBlogClick: post.onBlogClick
        };
    } else {
        // Fallback to placeholder image if neither exists
        return {
            id: post.id,
            title: post.title,
            author: post.author,
            description: post.description,
            tags: post.tags,
            imageSrc: "/placeholders/placeholder1.webp",            imageAlt: "Blog post image",            onBlogClick: post.onBlogClick
        };
    }
}

export default function BlogPage() {
    const [posts, setPosts] = useState<BlogPost[]>(defaultPosts);
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
        const fetchPosts = async () => {
            try {
                const apiUrl = process.env.NEXT_PUBLIC_API_URL;
                const projectId = process.env.NEXT_PUBLIC_PROJECT_ID;

                if (!apiUrl || !projectId) {
                    console.warn("NEXT_PUBLIC_API_URL or NEXT_PUBLIC_PROJECT_ID not configured, using default posts");
                    setIsLoading(false);
                    return;
                }

                const url = `${apiUrl}/posts/${projectId}`;
                const response = await fetch(url, {
                    method: "GET",                    headers: {
                        "Content-Type": "application/json"
                    },
                });

                if (response.ok) {
                    const data = await response.json();
                    if (Array.isArray(data) && data.length > 0) {
                        const mappedPosts = data.map((post: any) => ({
                            id: post.id || String(Math.random()),
                            title: post.title || "Untitled",                            author: post.author?.name || "Anonymous",                            description: post.excerpt || post.content?.slice(0, 100) || "No description available",                            tags: post.tags || [post.category || "General"],
                            imageSrc: post.imageUrl || "/placeholders/placeholder3.avif",                            imageAlt: post.imageAlt || post.title || "",                            onBlogClick: () => console.log(`Blog ${post.id} clicked`),
                        }));
                        setPosts(mappedPosts);
                    }
                } else {
                    console.warn(`API request failed with status ${response.status}, using default posts`);
                }
            } catch (error) {
                console.error("Error fetching posts:", error);
            } finally {
                setIsLoading(false);
            }
        };

        fetchPosts();
    }, []);

    // Convert BlogPost[] to BlogCard[]
    const blogCards: BlogCard[] = posts.map(convertToBlogCard);

    return (
        <ThemeProvider
            defaultButtonVariant="elastic-effect"
            defaultTextAnimation="entrance-slide"
            borderRadius="rounded"
            contentWidth="medium"
            sizing="largeSizeMediumTitles"
            background="circleGradient"
            cardStyle="elevated"
            primaryButtonStyle="shadow"
            secondaryButtonStyle="layered"
            headingFontWeight="medium"
        >
            <ReactLenis root>
                <div className="min-h-screen bg-background">
                    <NavbarStyleApple
                        brandName="BrewHaven"
                        navItems={[
                            { name: "Home", id: "hero" },
                            { name: "About", id: "about" },
                            { name: "Menu", id: "products" },
                            { name: "Reviews", id: "testimonials" },
                            { name: "Contact", id: "contact" }
                        ]}
                    />

                    {isLoading ? (
                        <div className="w-content-width mx-auto py-20 text-center">
                            <p className="text-foreground">Loading posts...</p>
                        </div>
                    ) : (
                        <BlogCardEleven
                            blogs={blogCards}
                            animationType="slide-up"
                            title="Coffee Chronicles"
                            description="Discover the latest insights, stories, and brewing wisdom from our coffee experts and passionate baristas."
                            textboxLayout="default"
                            useInvertedBackground="noInvert"
                            tag="Blog"
                        />
                    )}

                    <FooterBaseReveal
                        columns={[
                            {
                                title: "Coffee",                                items: [
                                    { label: "Our Menu", href: "products" },
                                    { label: "Bean Selection", href: "about" },
                                    { label: "Brewing Guide", href: "#" }
                                ]
                            },
                            {
                                title: "Experience",                                items: [
                                    { label: "About Us", href: "about" },
                                    { label: "Testimonials", href: "testimonials" },
                                    { label: "Events", href: "#" }
                                ]
                            },
                            {
                                title: "Connect",                                items: [
                                    { label: "Contact Us", href: "contact" },
                                    { label: "Social Media", href: "#" },
                                    { label: "Newsletter", href: "#" }
                                ]
                            }
                        ]}
                        copyrightText="© 2025 BrewHaven. All rights reserved. Crafted with passion for coffee lovers."
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}