"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 NavbarStyleFullscreen from '@/components/navbar/NavbarStyleFullscreen/NavbarStyleFullscreen';

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: ["Wood Processing", "Sustainability"],
        title: "Sustainable Wood Harvesting",        excerpt: "Learn about our eco-friendly approaches to wood harvesting and processing in Brazilian forests.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Sustainable wood harvesting in Brazilian forest",        authorName: "Carlos Silva",        authorAvatar: "/placeholders/placeholder3.avif",        date: "20 Jan 2025",        onBlogClick: () => console.log("Blog 1 clicked"),
    },
    {
        id: "2",        category: "Hardwoods",        title: "Premium Hardwood Selection",        excerpt: "Discover our premium selection of Brazilian hardwoods perfect for luxury furniture and construction.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Premium Brazilian hardwood samples",        authorName: "Maria Santos",        authorAvatar: "/placeholders/placeholder4.webp",        date: "18 Jan 2025",        onBlogClick: () => console.log("Blog 2 clicked"),
    },
    {
        id: "3",        category: "Certification",        title: "FSC Certification Process",        excerpt: "Understanding our Forest Stewardship Council certification and what it means for quality assurance.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "FSC certification documentation",        authorName: "João Pereira",        authorAvatar: "/placeholders/placeholder3.avif",        date: "15 Jan 2025",        onBlogClick: () => console.log("Blog 3 clicked"),
    },
    {
        id: "4",        category: ["Export", "Quality"],
        title: "International Export Standards",        excerpt: "How we maintain the highest quality standards when exporting Brazilian lumber worldwide.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Quality control in lumber export facility",        authorName: "Ana Costa",        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="icon-arrow"
            defaultTextAnimation="reveal-blur"
            borderRadius="soft"
            contentWidth="small"
            sizing="large"
            background="none"
            cardStyle="solid"
            primaryButtonStyle="flat"
            secondaryButtonStyle="layered"
            headingFontWeight="medium"
        >
            <ReactLenis root>
                <div className="min-h-screen bg-background">
                    <NavbarStyleFullscreen
                        brandName="Brazilian Lumber"
                        navItems={[
                            {"name":"Home","id":"/"},
                            {"name":"About","id":"about"},
                            {"name":"Products","id":"products"},
                            {"name":"Features","id":"features"},
                            {"name":"Contact","id":"contact"}
                        ]}
                        bottomLeftText="Sustainable Wood Solutions"
                        bottomRightText="contato@brazilianlumber.com"
                    />

                    {isLoading ? (
                        <div className="w-content-width mx-auto py-20 text-center">
                            <p className="text-foreground">Loading posts...</p>
                        </div>
                    ) : (
                        <BlogCardTwo
                            blogs={posts}
                            title="Wood Industry Insights"
                            description="Stay informed with the latest trends, sustainability practices, and innovations in the Brazilian lumber industry"
                            tag="Blog"
                            textboxLayout="default"
                            useInvertedBackground="noInvert"
                            carouselMode="buttons"
                            animationType="slide-up"
                        />
                    )}

                    <FooterBaseCard
                        logoText="Brazilian Lumber"
                        columns={[
                            {
                                "title":"Products",                                "items":[
                                    {"label":"Hardwoods","href":"#products"},
                                    {"label":"Softwoods","href":"#products"},
                                    {"label":"Plywood","href":"#products"},
                                    {"label":"Specialty Woods","href":"#products"}
                                ]
                            },
                            {
                                "title":"Company",                                "items":[
                                    {"label":"About Us","href":"#about"},
                                    {"label":"Our Process","href":"#features"},
                                    {"label":"Sustainability","href":"#features"},
                                    {"label":"Certifications","href":"#about"}
                                ]
                            },
                            {
                                "title":"Support",                                "items":[
                                    {"label":"Contact Us","href":"#contact"},
                                    {"label":"FAQ","href":"#faq"},
                                    {"label":"Shipping Info","href":"#faq"},
                                    {"label":"Returns","href":"#faq"}
                                ]
                            }
                        ]}
                        copyrightText="© 2025 Brazilian Lumber Co. | Premium Wood Solutions"
                        onPrivacyClick={null}
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}
