"use client";

import { useEffect, useState } from "react";
import ReactLenis from "lenis/react";
import BlogCardThree from '@/components/sections/blog/BlogCardThree';
import FooterBaseReveal from '@/components/sections/footer/FooterBaseReveal';
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: "Floral Design",        title: "The Art of Seasonal Arrangements",        excerpt: "Discover how to create stunning bouquets that capture the essence of each season with our expert florists' tips.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Seasonal flower arrangement with vibrant colors",        authorName: "Maria Petrov",        authorAvatar: "/placeholders/placeholder3.avif",        date: "20 Jan 2025",        onBlogClick: () => console.log("Blog 1 clicked"),
    },
    {
        id: "2",        category: "Care Tips",        title: "Extending Your Bouquet's Life",        excerpt: "Learn professional techniques to keep your flowers fresh and beautiful for weeks, not just days.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Fresh flowers being cared for",        authorName: "Anna Bloom",        authorAvatar: "/placeholders/placeholder4.webp",        date: "18 Jan 2025",        onBlogClick: () => console.log("Blog 2 clicked"),
    },
    {
        id: "3",        category: "Wedding Flowers",        title: "Perfect Wedding Bouquet Guide",        excerpt: "Everything you need to know about choosing the ideal wedding flowers for your special day.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Elegant wedding bouquet",        authorName: "Sophie Garden",        authorAvatar: "/placeholders/placeholder3.avif",        date: "15 Jan 2025",        onBlogClick: () => console.log("Blog 3 clicked"),
    },
    {
        id: "4",        category: "Occasions",        title: "Flowers for Every Celebration",        excerpt: "From birthdays to anniversaries, discover the perfect floral arrangements for life's special moments.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Colorful celebration flowers",        authorName: "David Rose",        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="pill"
            contentWidth="small"
            sizing="mediumSizeLargeTitles"
            background="aurora"
            cardStyle="inset"
            primaryButtonStyle="primary-glow"
            secondaryButtonStyle="layered"
            headingFontWeight="bold"
        >
            <ReactLenis root>
                <div className="min-h-screen bg-background">
                    <NavbarStyleCentered
                        brandName="KvitKa"
                        navItems={[
                            { name: "Home", id: "/home" },
                            { name: "Home", id: "home" },
                            { name: "Shop", id: "shop" },
                            { name: "About", id: "about" },
                            { name: "Blog", id: "blog" },
                            { name: "Contact", id: "contact" }
                        ]}
                        button={{
                            text: "Order Now",                            href: "shop"
                        }}
                    />

                    {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 tips about flowers, care, and special occasions"
                            textboxLayout="default"
                            useInvertedBackground="noInvert"
                            animationType="slide-up"
                            carouselMode="buttons"
                            tag="Blog"
                        />
                    )}

                    <FooterBaseReveal
                        copyrightText="© 2025 KvitKa Flowers. All rights reserved."
                        columns={[
                            {
                                title: "Shop",                                items: [
                                    { label: "All Flowers", href: "shop" },
                                    { label: "Bouquets", href: "shop" },
                                    { label: "Gifts", href: "shop" },
                                    { label: "Subscription", href: "shop" }
                                ]
                            },
                            {
                                title: "Company",                                items: [
                                    { label: "About Us", href: "about" },
                                    { label: "Blog", href: "blog" },
                                    { label: "Careers", href: "#" },
                                    { label: "Press", href: "#" }
                                ]
                            },
                            {
                                title: "Support",                                items: [
                                    { label: "Contact Us", href: "contact" },
                                    { label: "FAQ", href: "contact" },
                                    { label: "Delivery Info", href: "#" },
                                    { label: "Privacy Policy", href: "#" }
                                ]
                            }
                        ]}
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}