"use client";

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

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 Brewing",        excerpt: "Discover the perfect brewing techniques that bring out the best flavors in every cup.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Coffee brewing process",        authorName: "Sarah Mitchell",        authorAvatar: "/placeholders/placeholder3.avif",        date: "20 Jan 2025",        onBlogClick: () => console.log("Blog 1 clicked"),
    },
    {
        id: "2",        category: "Sustainability",        title: "Ethical Coffee Sourcing",        excerpt: "Learn about our commitment to fair trade and sustainable coffee farming practices.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Coffee farm",        authorName: "Michael Rodriguez",        authorAvatar: "/placeholders/placeholder4.webp",        date: "18 Jan 2025",        onBlogClick: () => console.log("Blog 2 clicked"),
    },
    {
        id: "3",        category: ["Fashion", "Merchandise"],
        title: "Coffee Culture Fashion",        excerpt: "Explore how coffee culture influences modern fashion trends and lifestyle choices.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Coffee themed apparel",        authorName: "Emma Thompson",        authorAvatar: "/placeholders/placeholder3.avif",        date: "15 Jan 2025",        onBlogClick: () => console.log("Blog 3 clicked"),
    },
    {
        id: "4",        category: "Business",        title: "Building a Coffee Community",        excerpt: "How local coffee shops create lasting connections and foster community engagement.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Coffee shop community",        authorName: "David Chen",        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="text-stagger"
            defaultTextAnimation="background-highlight"
            borderRadius="pill"
            contentWidth="compact"
            sizing="mediumLargeSizeLargeTitles"
            background="aurora"
            cardStyle="glass-elevated"
            primaryButtonStyle="diagonal-gradient"
            secondaryButtonStyle="glass"
            headingFontWeight="bold"
        >
            <ReactLenis root>
                <div className="min-h-screen bg-background">
                    <NavbarStyleCentered
                        brandName="Brew & Threads"
                        navItems={[
                            { name: "Home", id: "/home" },
                            { name: "Home", id: "hero" },
                            { name: "About", id: "about" },
                            { name: "Shop", id: "products" },
                            { name: "Reviews", id: "testimonials" },
                            { name: "Contact", id: "contact" }
                        ]}
                        button={{ text: "Order 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="Latest Coffee & Style Stories"
                            description="Discover the intersection of exceptional coffee and contemporary lifestyle through our curated articles"
                            textboxLayout="default"
                            useInvertedBackground="noInvert"
                            animationType="slide-up"
                            carouselMode="buttons"
                            tag="Blog"
                        />
                    )}

                    <FooterBaseCard
                        logoText="Brew & Threads"
                        columns={[
                            {
                                title: "Shop",                                items: [
                                    { label: "Coffee Beans", href: "products" },
                                    { label: "Merchandise", href: "products" },
                                    { label: "Gift Sets", href: "products" }
                                ]
                            },
                            {
                                title: "Company",                                items: [
                                    { label: "About Us", href: "about" },
                                    { label: "Our Story", href: "about" },
                                    { label: "Sustainability", href: "about" }
                                ]
                            },
                            {
                                title: "Support",                                items: [
                                    { label: "Contact", href: "contact" },
                                    { label: "FAQ", href: "contact" },
                                    { label: "Shipping Info", href: "contact" }
                                ]
                            },
                            {
                                title: "Connect",                                items: [
                                    { label: "Instagram", href: "https://instagram.com" },
                                    { label: "Facebook", href: "https://facebook.com" },
                                    { label: "Newsletter", href: "mailto:subscribe@brewandthreads.com" }
                                ]
                            }
                        ]}
                        copyrightText="© 2025 Brew & Threads. All rights reserved."
                        onPrivacyClick={null}
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}