"use client";

import { useEffect, useState } from "react";
import ReactLenis from "lenis/react";
import BlogCardThree from '@/components/sections/blog/BlogCardThree';
import FooterSimple from '@/components/sections/footer/FooterSimple';
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: "Italian Cuisine",        title: "The Art of Fresh Pasta",        excerpt: "Discover the traditional techniques of making authentic Italian pasta from scratch, passed down through generations.",        imageSrc: "https://img.b2bpic.net/free-photo/raw-pasta-near-dough_23-2147749572.jpg",        imageAlt: "Fresh pasta making",        authorName: "Chef Marco",        authorAvatar: "https://img.b2bpic.net/free-photo/chef-cooking-kitchen-while-wearing-professional-attire_23-2151208316.jpg",        date: "20 Jan 2025",        onBlogClick: () => console.log("Blog 1 clicked"),
    },
    {
        id: "2",        category: "Wine Pairing",        title: "Italian Wines: A Tasting Journey",        excerpt: "Explore the finest wines from Tuscany, Piedmont, and beyond. Learn how to pair them with your favorite Italian dishes.",        imageSrc: "https://img.b2bpic.net/free-photo/chef-holding-uncooked-pasta-hands_23-2148360857.jpg",        imageAlt: "Wine selection",        authorName: "Sommelier Sofia",        authorAvatar: "https://img.b2bpic.net/free-photo/high-angle-chef-male-kitchen_23-2148471868.jpg",        date: "18 Jan 2025",        onBlogClick: () => console.log("Blog 2 clicked"),
    },
    {
        id: "3",        category: "Chef's Corner",        title: "Seasonal Ingredients: Winter Edition",        excerpt: "Explore the bounty of Italian winter produce and how our chefs create exceptional dishes with seasonal ingredients.",        imageSrc: "https://img.b2bpic.net/free-photo/chef-arranging-raw-pasta_23-2148343569.jpg",        imageAlt: "Seasonal vegetables",        authorName: "Head Chef Giovanni",        authorAvatar: "https://img.b2bpic.net/free-photo/he-is-satisfied-from-his-life_329181-2789.jpg",        date: "15 Jan 2025",        onBlogClick: () => console.log("Blog 3 clicked"),
    },
    {
        id: "4",        category: "Food Culture",        title: "The History of Italian Cuisine",        excerpt: "A journey through centuries of culinary traditions that have shaped the Italian kitchen into what it is today.",        imageSrc: "https://img.b2bpic.net/free-photo/close-up-hands-with-pizza-cutter-utensils_23-2148296890.jpg",        imageAlt: "Traditional Italian kitchen",        authorName: "Food Historian Elena",        authorAvatar: "https://img.b2bpic.net/free-photo/portrait-confident-male-chef-kitchen_23-2147863584.jpg",        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 || "https://img.b2bpic.net/free-photo/raw-pasta-near-dough_23-2147749572.jpg",                            imageAlt: post.imageAlt || post.title || "",                            authorName: post.author?.name || "Anonymous",                            authorAvatar: post.author?.avatar || "https://img.b2bpic.net/free-photo/chef-cooking-kitchen-while-wearing-professional-attire_23-2151208316.jpg",                            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="background-highlight"
            borderRadius="rounded"
            contentWidth="medium"
            sizing="largeSizeMediumTitles"
            background="aurora"
            cardStyle="elevated"
            primaryButtonStyle="primary-glow"
            secondaryButtonStyle="layered"
            headingFontWeight="normal"
        >
            <ReactLenis root>
                <div className="min-h-screen bg-background">
                    <NavbarStyleCentered
                        brandName="NY Ouzzeur"
                        navItems={[
                            { name: "Home", id: "hero" },
                            { name: "About", id: "about" },
                            { name: "Menu", id: "features" },
                            { name: "Reviews", id: "testimonials" },
                            { name: "Reservations", id: "contact" }
                        ]}
                        button={{ text: "Book Table", 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="NY Ouzzeur Blog"
                            description="Discover culinary insights and the latest from our kitchen"
                            textboxLayout="default"
                            useInvertedBackground="noInvert"
                            animationType="slide-up"
                            carouselMode="buttons"
                            tag="Blog"
                        />
                    )}

                    <FooterSimple
                        columns={[
                            {
                                title: "Navigate",                                items: [
                                    { label: "Home", href: "#hero" },
                                    { label: "About", href: "#about" },
                                    { label: "Menu", href: "#features" },
                                    { label: "Reviews", href: "#testimonials" }
                                ]
                            },
                            {
                                title: "Dining",                                items: [
                                    { label: "Make a Reservation", href: "#contact" },
                                    { label: "Private Events", href: "#pricing" },
                                    { label: "Gift Cards", href: "#" },
                                    { label: "Contact Us", href: "#contact" }
                                ]
                            },
                            {
                                title: "Information",                                items: [
                                    { label: "Hours", href: "#" },
                                    { label: "Location", href: "#" },
                                    { label: "Careers", href: "#" },
                                    { label: "Press", href: "#" }
                                ]
                            },
                            {
                                title: "Legal",                                items: [
                                    { label: "Privacy Policy", href: "#" },
                                    { label: "Terms of Service", href: "#" },
                                    { label: "Accessibility", href: "#" }
                                ]
                            }
                        ]}
                        bottomLeftText="© 2025 NY Ouzzeur. All rights reserved. Crafted with excellence."
                        bottomRightText="Fine Dining in the Heart of New York"
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}
