"use client";

import { useEffect, useState } from "react";
import ReactLenis from "lenis/react";
import BlogCardTwo from '@/components/sections/blog/BlogCardTwo';
import FooterCard from '@/components/sections/footer/FooterCard';
import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import NavbarStyleFullscreen from '@/components/navbar/NavbarStyleFullscreen/NavbarStyleFullscreen';
import { Instagram, Twitter, Linkedin, Mail } from 'lucide-react';

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: "The Science Behind Effective Strength Training",        excerpt: "Discover the principles that make strength training effective, from progressive overload to proper recovery. Learn how to structure your training for maximum results.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Strength training form and technique",        authorName: "Personal Trainer",        authorAvatar: "/placeholders/placeholder3.avif",        date: "20 Jan 2025",        onBlogClick: () => console.log("Blog 1 clicked"),
    },
    {
        id: "2",        category: "Nutrition",        title: "Nutrition Strategies That Support Your Fitness Goals",        excerpt: "Learn how to fuel your body properly for optimal performance and recovery. From macronutrient timing to hydration strategies, discover nutrition fundamentals.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Healthy nutrition and meal planning",        authorName: "Personal Trainer",        authorAvatar: "/placeholders/placeholder4.webp",        date: "18 Jan 2025",        onBlogClick: () => console.log("Blog 2 clicked"),
    },
    {
        id: "3",        category: "Mindset",        title: "Building the Mental Strength to Achieve Your Fitness Goals",        excerpt: "Physical transformation starts with mental resilience. Explore practical strategies for overcoming obstacles, staying motivated, and building lasting habits.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Mental resilience and fitness mindset",        authorName: "Personal Trainer",        authorAvatar: "/placeholders/placeholder3.avif",        date: "15 Jan 2025",        onBlogClick: () => console.log("Blog 3 clicked"),
    },
    {
        id: "4",        category: "Recovery",        title: "Why Recovery is Just as Important as Training",        excerpt: "Rest and recovery aren't optional. Learn how sleep, stretching, and active recovery enhance your training results and prevent injury.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Recovery and rest strategies",        authorName: "Personal Trainer",        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 || "Personal Trainer",                            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="directional-hover"
            defaultTextAnimation="background-highlight"
            borderRadius="pill"
            contentWidth="medium"
            sizing="mediumLarge"
            background="aurora"
            cardStyle="gradient-bordered"
            primaryButtonStyle="inset-glow"
            secondaryButtonStyle="layered"
            headingFontWeight="semibold"
        >
            <ReactLenis root>
                <div className="min-h-screen bg-background">
                    <NavbarStyleFullscreen
                        navItems={[
                            { name: "Home", id: "/" },
                            { name: "About", id: "about" },
                            { name: "Certifications", id: "achievements" },
                            { name: "Services", id: "services" },
                            { name: "Approach", id: "philosophy" },
                            { name: "Contact", id: "contact" }
                        ]}
                        brandName="Personal Trainer"
                        bottomLeftText="Certified Professional"
                        bottomRightText="contact@trainer.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="Fitness Training Insights & Tips"
                            description="Expert advice on training, nutrition, recovery, and mindset from a certified personal trainer"
                            textboxLayout="default"
                            useInvertedBackground="noInvert"
                            animationType="slide-up"
                            carouselMode="buttons"
                            tag="Blog"
                        />
                    )}

                    <FooterCard
                        logoText="Personal Trainer"
                        copyrightText="© 2025 Professional Personal Training. All rights reserved."
                        socialLinks={[
                            { icon: Instagram, href: "https://instagram.com", ariaLabel: "Instagram" },
                            { icon: Twitter, href: "https://twitter.com", ariaLabel: "Twitter" },
                            { icon: Linkedin, href: "https://linkedin.com", ariaLabel: "LinkedIn" },
                            { icon: Mail, href: "mailto:contact@trainer.com", ariaLabel: "Email" }
                        ]}
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}