"use client";

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

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

const defaultPosts: BlogPost[] = [
    {
        id: "1",        tags: ["Coffee", "Brewing"],
        title: "The Art of Pour-Over Coffee",        excerpt: "Discover the secrets to brewing the perfect cup with our step-by-step pour-over guide.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Pour-over coffee brewing process",        authorName: "Elena Rodriguez",        date: "20 Jan 2025",        onBlogClick: () => console.log("Blog 1 clicked"),
    },
    {
        id: "2",        tags: ["Origins", "Sustainability"],
        title: "Ethiopian Coffee Heritage",        excerpt: "Explore the rich history and unique flavors of Ethiopian coffee beans and their impact on coffee culture.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Ethiopian coffee farm",        authorName: "Marcus Thompson",        date: "18 Jan 2025",        onBlogClick: () => console.log("Blog 2 clicked"),
    },
    {
        id: "3",        tags: ["Roasting", "Technique"],
        title: "Roasting Profiles Explained",        excerpt: "Learn how different roasting profiles affect flavor and find your perfect roast preference.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Coffee beans being roasted",        authorName: "Sarah Chen",        date: "15 Jan 2025",        onBlogClick: () => console.log("Blog 3 clicked"),
    },
    {
        id: "4",        tags: ["Equipment", "Guide"],
        title: "Home Espresso Setup Guide",        excerpt: "Everything you need to know about setting up your home espresso station for café-quality results.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Home espresso machine setup",        authorName: "David Kim",        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}`;
                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()),
                            tags: post.tags || [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",                            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="expand-hover"
            defaultTextAnimation="entrance-slide"
            borderRadius="sharp"
            contentWidth="medium"
            sizing="medium"
            background="floatingGradient"
            cardStyle="glass-depth"
            primaryButtonStyle="gradient"
            secondaryButtonStyle="solid"
            headingFontWeight="extrabold"
        >
            <ReactLenis root>
                <div className="min-h-screen bg-background">
                    <NavbarStyleApple
                        brandName="Artisan Brew"
                        navItems={[
                            { name: "About", id: "about" },
                            { name: "Menu", id: "menu" },
                            { 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>
                    ) : (
                        <BlogCardTwo
                            blogs={posts}
                            title="Coffee Chronicles"
                            description="Discover the stories behind every brew, from bean to cup"
                            textboxLayout="default"
                            useInvertedBackground="noInvert"
                            carouselMode="buttons"
                            animationType="slide-up"
                            tag="Blog"
                        />
                    )}

                    <FooterBaseCard
                        logoText="Artisan Brew"
                        columns={[
                            {
                                title: "Coffee",                                items: [
                                    { label: "Our Menu", href: "#menu" },
                                    { label: "Bean Origins", href: "#" },
                                    { label: "Brewing Guide", href: "#" }
                                ]
                            },
                            {
                                title: "Community",                                items: [
                                    { label: "About Us", href: "#about" },
                                    { label: "Our Story", href: "#about" },
                                    { label: "Careers", href: "#" }
                                ]
                            },
                            {
                                title: "Connect",                                items: [
                                    { label: "Contact", href: "#contact" },
                                    { label: "Instagram", href: "#" },
                                    { label: "Newsletter", href: "#" }
                                ]
                            },
                            {
                                title: "Support",                                items: [
                                    { label: "FAQs", href: "#" },
                                    { label: "Bulk Orders", href: "#" },
                                    { label: "Corporate Gifts", href: "#" }
                                ]
                            }
                        ]}
                        copyrightText="© 2025 Artisan Brew. Crafted with care and exceptional coffee."
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}