"use client";

import { useEffect, useState } from "react";
import ReactLenis from "lenis/react";
import BlogCardThree from '@/components/sections/blog/BlogCardThree';
import FooterLogoReveal from '@/components/sections/footer/FooterLogoReveal';
import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import NavbarStyleCentered from '@/components/navbar/NavbarStyleCentered/NavbarStyleCentered';

type BlogPost = {
    id: string;
    category: string;
    title: string;
    excerpt: string;
    imageSrc: string;
    imageAlt?: string;
    authorName?: string;
    authorAvatar?: string;
    date?: string;
    onBlogClick?: () => void;
};

const defaultPosts: BlogPost[] = [
    {
        id: "1",        category: "Baking",        title: "The Art of Sourdough",        excerpt: "Discover the secrets behind creating the perfect sourdough bread with our traditional techniques.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Fresh sourdough bread",        authorName: "Marie Dubois",        authorAvatar: "/placeholders/placeholder3.avif",        date: "20 Jan 2025",        onBlogClick: () => console.log("Blog 1 clicked"),
    },
    {
        id: "2",        category: "Ingredients",        title: "Sourcing Premium Flour",        excerpt: "Learn about our carefully selected organic flours and how they make all the difference in taste.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Organic flour varieties",        authorName: "Jean Baptiste",        authorAvatar: "/placeholders/placeholder4.webp",        date: "18 Jan 2025",        onBlogClick: () => console.log("Blog 2 clicked"),
    },
    {
        id: "3",        category: "Pastries",        title: "Croissant Making Masterclass",        excerpt: "Follow our step-by-step guide to creating buttery, flaky croissants that rival those from Paris.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Golden croissants",        authorName: "Chef Antoine",        authorAvatar: "/placeholders/placeholder3.avif",        date: "15 Jan 2025",        onBlogClick: () => console.log("Blog 3 clicked"),
    },
    {
        id: "4",        category: "Tradition",        title: "100 Years of Baking Heritage",        excerpt: "Explore the rich history of our family bakery and the recipes passed down through generations.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Vintage bakery photo",        authorName: "Isabella Romano",        authorAvatar: "/placeholders/placeholder4.webp",        date: "12 Jan 2025",        onBlogClick: () => console.log("Blog 4 clicked"),
    },
];

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}?status=published`;
                const response = await fetch(url, {
                    method: "GET",                    headers: {
                        "Content-Type": "application/json"},
                });

                if (response.ok) {
                    const resp = await response.json();
                    const data = resp.data;
                    if (Array.isArray(data) && data.length > 0) {
                        const mappedPosts = data.map((post: any) => ({
                            id: post.id || String(Math.random()),
                            category: post.category || "General",                            title: post.title || "Untitled",                            excerpt: post.excerpt || post.content.slice(0, 30) || "",                            imageSrc: post.imageUrl || "/placeholders/placeholder3.avif",                            imageAlt: post.imageAlt || post.title || "",                            authorName: post.author?.name || "Anonymous",                            authorAvatar: post.author?.avatar || "/placeholders/placeholder3.avif",                            date: post.date || post.createdAt || new Date().toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" }),
                            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();
    }, []);

    return (
        <ThemeProvider
            defaultButtonVariant="directional-hover"
            defaultTextAnimation="reveal-blur"
            borderRadius="pill"
            contentWidth="mediumLarge"
            sizing="largeSmallSizeMediumTitles"
            background="aurora"
            cardStyle="layered-gradient"
            primaryButtonStyle="radial-glow"
            secondaryButtonStyle="radial-glow"
            headingFontWeight="medium"
        >
            <ReactLenis root>
                <div className="min-h-screen bg-background">
                    <NavbarStyleCentered
                        brandName="Artisan Bakery"
                        navItems={[
                            { name: "Home", id: "/home" },
                            { name: "Home", id: "hero" },
                            { name: "About", id: "about" },
                            { name: "Products", id: "products" },
                            { name: "Process", id: "process" },
                            { name: "Reviews", id: "testimonials" }
                        ]}
                        button={{ text: "Order Now", href: "contact" }}
                    />

                    {isLoading ? (
                        <div className="w-content-width mx-auto py-20 text-center">
                            <p className="text-foreground">Loading posts...</p>
                        </div>
                    ) : (
                        <BlogCardThree
                            blogs={posts}
                            title="Featured Articles"
                            description="Explore our latest insights and stories from the world of artisan baking"
                            textboxLayout="default"
                            useInvertedBackground="noInvert"
                            carouselMode="buttons"
                            animationType="slide-up"
                            tag="Blog"
                        />
                    )}

                    <FooterLogoReveal
                        logoText="ARTISAN BAKERY"
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}