"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: "Training",        title: "Advanced Dressage Techniques",        excerpt: "Master the art of dressage with our comprehensive training program for horse and rider.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Dressage training session",        authorName: "Sarah Johnson",        authorAvatar: "/placeholders/placeholder3.avif",        date: "20 Jan 2025",        onBlogClick: () => console.log("Blog 1 clicked"),
    },
    {
        id: "2",        category: ["Care", "Health"],
        title: "Equine Nutrition Essentials",        excerpt: "Learn the fundamentals of proper horse nutrition for optimal health and performance.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Horse nutrition guide",        authorName: "Dr. Michael Thompson",        authorAvatar: "/placeholders/placeholder4.webp",        date: "18 Jan 2025",        onBlogClick: () => console.log("Blog 2 clicked"),
    },
    {
        id: "3",        category: "Events",        title: "Show Jumping Competition Tips",        excerpt: "Prepare for your next competition with expert advice from professional show jumpers.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Show jumping event",        authorName: "Emma Wilson",        authorAvatar: "/placeholders/placeholder3.avif",        date: "15 Jan 2025",        onBlogClick: () => console.log("Blog 3 clicked"),
    },
    {
        id: "4",        category: ["Membership", "Community"],
        title: "Benefits of Club Membership",        excerpt: "Discover the exclusive benefits and opportunities available to Kobula Club members.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Club membership benefits",        authorName: "Robert 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 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="slide-background"
            defaultTextAnimation="background-highlight"
            borderRadius="rounded"
            contentWidth="mediumLarge"
            sizing="largeSmallSizeLargeTitles"
            background="circleGradient"
            cardStyle="soft-shadow"
            primaryButtonStyle="gradient"
            secondaryButtonStyle="solid"
            headingFontWeight="semibold"
        >
            <ReactLenis root>
                <div className="min-h-screen bg-background">
                    <NavbarStyleFullscreen
                        brandName="Kobula"
                        navItems={[
                            { name: "Home", id: "/" },
                            { name: "About", id: "about" },
                            { name: "Services", id: "features" },
                            { name: "Team", id: "team" },
                            { name: "Contact", id: "contact" }
                        ]}
                        bottomLeftText="Equestrian Excellence"
                        bottomRightText="info@kobulaclub.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="Kobula Club Insights"
                            description="Stay updated with the latest news, training tips, and insights from the world of equestrian excellence"
                            textboxLayout="default"
                            useInvertedBackground="noInvert"
                            carouselMode="buttons"
                            animationType="slide-up"
                            tag="Blog"
                        />
                    )}

                    <FooterBaseCard
                        logoText="Kobula"
                        columns={[
                            {
                                title: "Club",                                items: [
                                    { label: "About Us", href: "#about" },
                                    { label: "Our Team", href: "#team" },
                                    { label: "Facilities", href: "#features" },
                                    { label: "Events", href: "#metrics" }
                                ]
                            },
                            {
                                title: "Membership",                                items: [
                                    { label: "Join Kobula", href: "#contact" },
                                    { label: "Lesson Programs", href: "#features" },
                                    { label: "Boarding Options", href: "#features" },
                                    { label: "FAQ", href: "#faq" }
                                ]
                            },
                            {
                                title: "Contact",                                items: [
                                    { label: "Email: info@kobulaclub.com", href: "mailto:info@kobulaclub.com" },
                                    { label: "Phone: (555) 123-4567", href: "tel:+15551234567" },
                                    { label: "Hours: Tue-Sun 10am-6pm", href: "#" },
                                    { label: "Location: Find Us", href: "#" }
                                ]
                            },
                            {
                                title: "Follow",                                items: [
                                    { label: "Instagram", href: "https://instagram.com" },
                                    { label: "Facebook", href: "https://facebook.com" },
                                    { label: "YouTube", href: "https://youtube.com" }
                                ]
                            }
                        ]}
                        copyrightText="© 2025 Kobula Horse Club. All rights reserved."
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}