"use client";

import { useEffect, useState } from "react";
import ReactLenis from "lenis/react";
import BlogCardThree from '@/components/sections/blog/BlogCardThree';
import FooterBase from '@/components/sections/footer/FooterBase';
import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import type { FooterColumn } from "@/components/shared/FooterColumns";
import NavbarLayoutFloatingInline from '@/components/navbar/NavbarLayoutFloatingInline';

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 Modern Floral Arrangements",        excerpt: "Discover the techniques and inspiration behind contemporary floral design that captivates.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Beautiful modern floral arrangement",        authorName: "Maria Elena",        authorAvatar: "/placeholders/placeholder3.avif",        date: "20 Jan 2025",        onBlogClick: () => console.log("Blog 1 clicked"),
    },
    {
        id: "2",        category: "Wedding Florals",        title: "Creating Unforgettable Wedding Bouquets",        excerpt: "Learn the secrets to designing wedding florals that tell your unique love story.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Elegant wedding bouquet",        authorName: "Isabella Rose",        authorAvatar: "/placeholders/placeholder4.webp",        date: "18 Jan 2025",        onBlogClick: () => console.log("Blog 2 clicked"),
    },
    {
        id: "3",        category: "Seasonal Flowers",        title: "Spring Blooms That Transform Spaces",        excerpt: "Explore how seasonal flowers can breathe new life into any environment.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Vibrant spring flower arrangement",        authorName: "Carlos Mendez",        authorAvatar: "/placeholders/placeholder3.avif",        date: "15 Jan 2025",        onBlogClick: () => console.log("Blog 3 clicked"),
    },
    {
        id: "4",        category: "Flower Care",        title: "Essential Tips for Long-Lasting Arrangements",        excerpt: "Master the art of flower care to keep your arrangements fresh and beautiful longer.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Fresh flower care demonstration",        authorName: "Ana Sofia",        authorAvatar: "/placeholders/placeholder4.webp",        date: "12 Jan 2025",        onBlogClick: () => console.log("Blog 4 clicked"),
    },
];

const footerColumns: FooterColumn[] = [
    {
        title: "Services",        items: [
            { label: "Custom Bouquets", href: "services" },
            { label: "Wedding Flowers", href: "services" },
            { label: "Event Design", href: "services" },
            { label: "Same-Day Delivery", href: "services" }
        ]
    },
    {
        title: "Company",        items: [
            { label: "About Us", href: "about" },
            { label: "Gallery", href: "gallery" },
            { label: "Contact", href: "contact" },
            { label: "FAQs", href: "contact" }
        ]
    },
    {
        title: "Connect",        items: [
            { label: "Instagram", href: "https://instagram.com" },
            { label: "Facebook", href: "https://facebook.com" },
            { label: "Email", href: "mailto:hello@amigoflowers.com" },
            { label: "Phone", href: "tel:+1234567890" }
        ]
    }
];

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="elastic-effect"
            defaultTextAnimation="reveal-blur"
            borderRadius="rounded"
            contentWidth="compact"
            sizing="largeSmall"
            background="aurora"
            cardStyle="glass-elevated"
            primaryButtonStyle="diagonal-gradient"
            secondaryButtonStyle="solid"
            headingFontWeight="normal"
        >
            <ReactLenis root>
                <div className="min-h-screen bg-background">
                    <NavbarLayoutFloatingInline
                        brandName="Amigo"
                        navItems={[
                            { name: "Home", id: "/" },
                            { name: "Gallery", id: "gallery" },
                            { name: "Services", id: "services" },
                            { 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>
                    ) : (
                        <BlogCardThree
                            blogs={posts}
                            title="Featured Floral Articles"
                            description="Discover the artistry and passion behind every bloom with our expert insights"
                            tag="Blog"
                            textboxLayout="default"
                            useInvertedBackground="noInvert"
                            animationType="slide-up"
                            carouselMode="buttons"
                            uniformGridCustomHeightClasses="min-h-[600px]"
                        />
                    )}

                    <FooterBase
                        logoText="Amigo Flowers"
                        copyrightText="© 2025 Amigo Flowers Studio. All rights reserved."
                        columns={footerColumns}
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}