"use client";

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

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: "Ontwerp",        title: "UX review presentaties",        excerpt: "Hoe create je indrukwekkende presentaties die je collega's wow en je managers imponeren?",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Abstract ontwerp met paarse en zilveren tinten",        authorName: "Olivia Rhye",        authorAvatar: "/placeholders/placeholder3.avif",        date: "20 Jan 2025",        onBlogClick: () => console.log("Blog 1 clicked"),
    },
    {
        id: "2",        category: "Ontwikkeling",        title: "Bouw schaalbare applicaties",        excerpt: "Leer de best practices voor het bouwen van applicaties die miljoenen gebruikers aankunnen.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Ontwikkelingswerkruimte",        authorName: "John Smith",        authorAvatar: "/placeholders/placeholder4.webp",        date: "18 Jan 2025",        onBlogClick: () => console.log("Blog 2 clicked"),
    },
    {
        id: "3",        category: "Marketing",        title: "Essentiële inhoudsstrategie",        excerpt: "Ontdek hoe je een inhoudsstrategie maakt die engagement en conversies voortdrijft.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Marketingstrategie bord",        authorName: "Sarah Johnson",        authorAvatar: "/placeholders/placeholder3.avif",        date: "15 Jan 2025",        onBlogClick: () => console.log("Blog 3 clicked"),
    },
    {
        id: "4",        category: "Product",        title: "Productbeheer 101",        excerpt: "Alles wat je moet weten om een effectieve productmanager in 2025 te worden.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Productplanningssessie",        authorName: "Mike Davis",        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 of NEXT_PUBLIC_PROJECT_ID niet geconfigureerd, gebruik standaard 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 || "Algemeen",                            title: post.title || "Zonder titel",                            excerpt: post.excerpt || post.content.slice(0, 30) || "",                            imageSrc: post.imageUrl || "/placeholders/placeholder3.avif",                            imageAlt: post.imageAlt || post.title || "",                            authorName: post.author?.name || "Anoniem",                            authorAvatar: post.author?.avatar || "/placeholders/placeholder3.avif",                            date: post.date || post.createdAt || new Date().toLocaleDateString("nl-NL", { day: "numeric", month: "short", year: "numeric" }),
                            onBlogClick: () => console.log(`Blog ${post.id} clicked`),
                        }));
                        setPosts(mappedPosts);
                    }
                } else {
                    console.warn(`API-verzoek mislukt met status ${response.status}, gebruik standaard posts`);
                }
            } catch (error) {
                console.error("Fout bij het ophalen van posts:", error);
            } finally {
                setIsLoading(false);
            }
        };

        fetchPosts();
    }, []);

    return (
        <ThemeProvider
            defaultButtonVariant="elastic-effect"
            defaultTextAnimation="entrance-slide"
            borderRadius="rounded"
            contentWidth="mediumSmall"
            sizing="largeSizeMediumTitles"
            background="floatingGradient"
            cardStyle="gradient-mesh"
            primaryButtonStyle="diagonal-gradient"
            secondaryButtonStyle="solid"
            headingFontWeight="bold"
        >
            <ReactLenis root>
                <div className="min-h-screen bg-background">
                    <NavbarStyleFullscreen
                        brandName="Geüpcycled Threads"
                        navItems={[
                            { name: "Home", id: "/home" },
                            { name: "Home", id: "home" },
                            { name: "Over mij", id: "about" },
                            { name: "Shop", id: "products" },
                            { name: "Proces", id: "process" },
                            { name: "Contact", id: "contact" }
                        ]}
                        bottomLeftText="Duurzame Mode"
                        bottomRightText="hallo@geupycyledthreads.nl"
                    />

                    {isLoading ? (
                        <div className="w-content-width mx-auto py-20 text-center">
                            <p className="text-foreground">Posts laden...</p>
                        </div>
                    ) : (
                        <BlogCardTwo
                            blogs={posts}
                            title="Inzichten Duurzame Mode"
                            description="Ontdek de nieuwste trends en tips in duurzame mode en upcycling"
                            textboxLayout="default"
                            useInvertedBackground="noInvert"
                            animationType="slide-up"
                            carouselMode="buttons"
                        />
                    )}

                    <FooterLogoReveal
                        logoText="Geüpcycled Threads"
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}
