"use client";

import { useEffect, useState } from "react";
import ReactLenis from "lenis/react";
import BlogCardTwo from '@/components/sections/blog/BlogCardTwo';
import FooterBase from '@/components/sections/footer/FooterBase';
import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import type { FooterColumn } from "@/components/shared/FooterColumns";
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: ["Design", "UX"],
        title: "Cozy Living: Design Tips for Your Home",        excerpt: "Transform your space into a cozy sanctuary with these essential design tips and blanket styling ideas.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Cozy living room with blankets",        authorName: "Sarah Williams",        authorAvatar: "/placeholders/placeholder3.avif",        date: "20 Jan 2025",        onBlogClick: () => console.log("Blog 1 clicked"),
    },
    {
        id: "2",        category: "Home Decor",        title: "Seasonal Comfort: Choosing the Right Blanket",        excerpt: "Discover how to select the perfect blanket for every season and create year-round comfort in your home.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Seasonal blanket collection",        authorName: "Emily Chen",        authorAvatar: "/placeholders/placeholder4.webp",        date: "18 Jan 2025",        onBlogClick: () => console.log("Blog 2 clicked"),
    },
    {
        id: "3",        category: ["Lifestyle", "Wellness"],
        title: "The Science of Comfort: Why Blankets Matter",        excerpt: "Explore the psychology and science behind why blankets make us feel secure and comfortable.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Person wrapped in blanket",        authorName: "Dr. Michael Johnson",        authorAvatar: "/placeholders/placeholder3.avif",        date: "15 Jan 2025",        onBlogClick: () => console.log("Blog 3 clicked"),
    },
    {
        id: "4",        category: "Care Tips",        title: "Blanket Care 101: Keeping Your Comfort Fresh",        excerpt: "Learn the best practices for washing, storing, and maintaining your favorite blankets to ensure they last.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Clean folded blankets",        authorName: "Lisa Rodriguez",        authorAvatar: "/placeholders/placeholder4.webp",        date: "12 Jan 2025",        onBlogClick: () => console.log("Blog 4 clicked"),
    },
];

const footerColumns: FooterColumn[] = [
    {
        title: "Shop",        items: [
            { label: "All Products", href: "products" },
            { label: "Best Sellers", href: "products" },
            { label: "New Arrivals", href: "products" },
        ],
    },
    {
        title: "Company",        items: [
            { label: "About Us", href: "about" },
            { label: "Contact", href: "contact" },
            { label: "Blog", href: "#" },
        ],
    },
    {
        title: "Support",        items: [
            { label: "FAQ", href: "faq" },
            { label: "Shipping Info", href: "#" },
            { label: "Returns", href: "#" },
        ],
    },
];

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="shift-hover"
            defaultTextAnimation="reveal-blur"
            borderRadius="pill"
            contentWidth="smallMedium"
            sizing="large"
            background="floatingGradient"
            cardStyle="gradient-radial"
            primaryButtonStyle="primary-glow"
            secondaryButtonStyle="glass"
            headingFontWeight="bold"
        >
            <ReactLenis root>
                <div className="min-h-screen bg-background">
                    <NavbarLayoutFloatingOverlay
                        brandName="Cozy Blankets"
                        navItems={[
                            {"name":"Home","id":"/home"},
                            {"name":"Products","id":"products"},
                            {"name":"About","id":"about"},
                            {"name":"Features","id":"features"},
                            {"name":"Reviews","id":"testimonials"},
                            {"name":"FAQ","id":"faq"}
                        ]}
                        button={{"text":"Shop Now","href":"products"}}
                    />

                    {isLoading ? (
                        <div className="w-content-width mx-auto py-20 text-center">
                            <p className="text-foreground">Loading posts...</p>
                        </div>
                    ) : (
                        <BlogCardTwo
                            blogs={posts}
                            title="Comfort & Style Blog"
                            description="Discover tips, insights, and stories about creating the perfect cozy environment with our premium blankets"
                            textboxLayout="default"
                            useInvertedBackground="noInvert"
                            animationType="slide-up"
                            carouselMode="buttons"
                        />
                    )}

                    <FooterBase
                        logoText="Cozy Blankets"
                        copyrightText="© 2025 Cozy Blankets. All rights reserved."
                        columns={[
                            {
                                "title":"Shop",                                "items":[
                                    {"label":"All Products","href":"products"},
                                    {"label":"Best Sellers","href":"products"},
                                    {"label":"New Arrivals","href":"products"}
                                ]
                            },
                            {
                                "title":"Company",                                "items":[
                                    {"label":"About Us","href":"about"},
                                    {"label":"Contact","href":"contact"},
                                    {"label":"Blog","href":"#"}
                                ]
                            },
                            {
                                "title":"Support",                                "items":[
                                    {"label":"FAQ","href":"faq"},
                                    {"label":"Shipping Info","href":"#"},
                                    {"label":"Returns","href":"#"}
                                ]
                            }
                        ]}
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}