"use client";

import { useEffect, useState } from "react";
import ReactLenis from "lenis/react";
import BlogCardTwo from '@/components/sections/blog/BlogCardTwo';
import FooterBaseCard from '@/components/sections/footer/FooterBaseCard';
import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import NavbarLayoutFloatingOverlay from '@/components/navbar/NavbarLayoutFloatingOverlay/NavbarLayoutFloatingOverlay';

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

const defaultPosts: BlogPost[] = [
    {
        id: "1",        category: ["Coffee", "Brewing"],
        title: "The Art of Coffee Brewing",        excerpt: "Discover the perfect brewing techniques to extract the best flavors from your coffee beans.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Coffee brewing process",        authorName: "Maria Santos",        authorAvatar: "/placeholders/placeholder3.avif",        date: "20 Jan 2025",        onBlogClick: () => console.log("Blog 1 clicked"),
    },
    {
        id: "2",        category: "Sustainability",        title: "Sustainable Coffee Practices",        excerpt: "Learn how we source our beans ethically and support coffee farming communities worldwide.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Coffee farm sustainability",        authorName: "James Rodriguez",        authorAvatar: "/placeholders/placeholder4.webp",        date: "18 Jan 2025",        onBlogClick: () => console.log("Blog 2 clicked"),
    },
    {
        id: "3",        category: ["Recipes", "Barista"],
        title: "Signature Latte Recipes",        excerpt: "Master the craft of creating perfect lattes with our signature recipes and techniques.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Latte art creation",        authorName: "Sophie Chen",        authorAvatar: "/placeholders/placeholder3.avif",        date: "15 Jan 2025",        onBlogClick: () => console.log("Blog 3 clicked"),
    },
    {
        id: "4",        category: "Culture",        title: "Coffee Culture Around the World",        excerpt: "Explore the rich traditions and unique coffee cultures from different countries and regions.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Global coffee culture",        authorName: "Alex Thompson",        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="hover-bubble"
            defaultTextAnimation="entrance-slide"
            borderRadius="rounded"
            contentWidth="smallMedium"
            sizing="largeSmallSizeLargeTitles"
            background="floatingGradient"
            cardStyle="solid"
            primaryButtonStyle="gradient"
            secondaryButtonStyle="layered"
            headingFontWeight="light"
        >
            <ReactLenis root>
                <div className="min-h-screen bg-background">
                    <NavbarLayoutFloatingOverlay
                        brandName="Morn Ing"
                        navItems={[
                            { name: "Home", id: "/" },
                            { name: "About", id: "about" },
                            { name: "Menu", id: "products" },
                            { name: "Products", id: "/products" },
                            { name: "Testimonials", id: "testimonials" },
                            { name: "Contact", id: "contact" }
                        ]}
                        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>
                    ) : (
                        <BlogCardTwo
                            blogs={posts}
                            title="Coffee Chronicles"
                            description="Discover the world of coffee through our expert insights, brewing guides, and stories from our passionate team."
                            tag="Blog"
                            textboxLayout="default"
                            useInvertedBackground="noInvert"
                            carouselMode="buttons"
                            animationType="slide-up"
                        />
                    )}

                    <FooterBaseCard
                        logoText="Morn Ing"
                        columns={[
                            {
                                title: "Company",                                items: [
                                    { label: "About Us", href: "#about" },
                                    { label: "Our Story", href: "#about" },
                                    { label: "Sustainability", href: "#" }
                                ]
                            },
                            {
                                title: "Menu",                                items: [
                                    { label: "Coffee Drinks", href: "#products" },
                                    { label: "Pastries", href: "#" },
                                    { label: "Beans & Gear", href: "#" }
                                ]
                            },
                            {
                                title: "Connect",                                items: [
                                    { label: "Contact", href: "#contact" },
                                    { label: "Instagram", href: "https://instagram.com" },
                                    { label: "Events", href: "#" }
                                ]
                            },
                            {
                                title: "Visit",                                items: [
                                    { label: "123 Coffee Street, Downtown", href: "#" },
                                    { label: "hello@morning-coffee.com", href: "mailto:hello@morning-coffee.com" },
                                    { label: "(555) COFFEE-1", href: "tel:+15556633335" }
                                ]
                            }
                        ]}
                        copyrightText="© 2025 Morn Ing Coffee Shop. All rights reserved."
                        onPrivacyClick={null}
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}