"use client";

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

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", "Coffee"],
        title: "The Art of Coffee Roasting",        excerpt: "Discover the secrets behind our perfectly roasted beans and the craft that goes into every batch.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Coffee roasting process",        authorName: "Sarah Mitchell",        authorAvatar: "/placeholders/placeholder3.avif",        date: "20 Jan 2025",        onBlogClick: () => console.log("Blog 1 clicked"),
    },
    {
        id: "2",        category: "Brewing",        title: "Pour Over Perfection",        excerpt: "Master the pour-over technique with our step-by-step guide to brewing exceptional coffee at home.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Pour over coffee brewing",        authorName: "Marcus Chen",        authorAvatar: "/placeholders/placeholder4.webp",        date: "18 Jan 2025",        onBlogClick: () => console.log("Blog 2 clicked"),
    },
    {
        id: "3",        category: ["Origins", "Sustainability"],
        title: "Bean Origins & Fair Trade",        excerpt: "Learn about our commitment to ethical sourcing and the incredible farmers who grow our coffee.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Coffee farm sustainability",        authorName: "Elena Rodriguez",        authorAvatar: "/placeholders/placeholder3.avif",        date: "15 Jan 2025",        onBlogClick: () => console.log("Blog 3 clicked"),
    },
    {
        id: "4",        category: "Cafe Culture",        title: "Creating Community Spaces",        excerpt: "How BrewHaven designs spaces that bring people together over exceptional coffee experiences.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Coffee shop interior",        authorName: "David Park",        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="background-highlight"
            borderRadius="soft"
            contentWidth="smallMedium"
            sizing="large"
            background="aurora"
            cardStyle="gradient-radial"
            primaryButtonStyle="flat"
            secondaryButtonStyle="layered"
            headingFontWeight="extrabold"
        >
            <ReactLenis root>
                <div className="min-h-screen bg-background">
                    <NavbarLayoutFloatingInline
                        brandName="BrewHaven"
                        navItems={[
                            { name: "Home", id: "/home" },
                            { name: "About", id: "about" },
                            { name: "Menu", id: "products" },
                            { name: "Process", id: "features" },
                            { name: "Contact", id: "contact" }
                        ]}
                        button={{
                            text: "Visit Us",                            href: "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 Stories & Insights"
                            description="Discover the world of coffee through our expert insights, brewing guides, and stories from the heart of BrewHaven."
                            textboxLayout="default"
                            useInvertedBackground="noInvert"
                            animationType="slide-up"
                            carouselMode="buttons"
                        />
                    )}

                    <FooterSimple
                        columns={[
                            {
                                title: "Navigate",                                items: [
                                    { label: "Home", href: "#hero" },
                                    { label: "About", href: "#about" },
                                    { label: "Menu", href: "#products" },
                                    { label: "Contact", href: "#contact" }
                                ]
                            },
                            {
                                title: "Visit Us",                                items: [
                                    { label: "123 Coffee Lane, Brew City, BC 45678" },
                                    { label: "Mon-Fri: 6:30am - 8:00pm" },
                                    { label: "Sat-Sun: 8:00am - 9:00pm" },
                                    { label: "(555) 123-4567" }
                                ]
                            },
                            {
                                title: "Follow Us",                                items: [
                                    { label: "Instagram", href: "https://instagram.com" },
                                    { label: "Facebook", href: "https://facebook.com" },
                                    { label: "Twitter", href: "https://twitter.com" }
                                ]
                            }
                        ]}
                        bottomLeftText="© 2025 BrewHaven Coffee. All rights reserved."
                        bottomRightText="Roasting Excellence, Brewing Passion"
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}