"use client";

import { useEffect, useState } from "react";
import ReactLenis from "lenis/react";
import TestimonialCardTwo from '@/components/sections/testimonial/TestimonialCardTwo';
import FooterCard from '@/components/sections/footer/FooterCard';
import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import NavbarStyleApple from '@/components/navbar/NavbarStyleApple/NavbarStyleApple';
import { PawPrint, Facebook, Instagram, Twitter } from 'lucide-react';

type BlogPost = {
    id: string;
    name: string;
    role: string;
    testimonial: string;
    imageSrc?: string;
    imageAlt?: string;
};

const defaultPosts: BlogPost[] = [
    {
        id: "1",        name: "Finding Forever Homes",        role: "Success Stories from Happy Paws",        testimonial: "Heartwarming stories of rescued animals finding their perfect families through our adoption program. Discover how love transforms lives.",        imageSrc: "/placeholders/placeholder1.webp",        imageAlt: "Happy dog with new family"
    },
    {
        id: "2",        name: "Pet Care Tips",        role: "Keeping Your Furry Friends Healthy",        testimonial: "Essential health and wellness tips from our veterinary team to ensure your pets live their best lives. Expert advice for new pet parents.",        imageSrc: "/placeholders/placeholder1.webp",        imageAlt: "Veterinarian examining a cat"
    },
    {
        id: "3",        name: "Volunteer Spotlight",        role: "Making a Difference Together",        testimonial: "Meet our amazing volunteers who dedicate their time to helping animals in need find loving homes. Community heroes making an impact.",        imageSrc: "/placeholders/placeholder1.webp",        imageAlt: "Volunteers playing with shelter dogs"
    },
    {
        id: "4",        name: "Animal Behavior Guide",        role: "Understanding Your New Pet",        testimonial: "Learn to decode your pet's behavior and build a stronger bond with your new four-legged family member. Professional training insights.",        imageSrc: "/placeholders/placeholder1.webp",        imageAlt: "Dog trainer working with a puppy"
    }
];

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}`;
                const response = await fetch(url, {
                    method: "GET",                    headers: {
                        "Content-Type": "application/json"
                    },
                });

                if (response.ok) {
                    const data = await response.json();
                    if (Array.isArray(data) && data.length > 0) {
                        const mappedPosts = data.map((post: any) => ({
                            id: post.id || String(Math.random()),
                            name: post.title || "Untitled",                            role: post.author?.name || "Happy Paws Story",                            testimonial: post.excerpt || post.content?.slice(0, 150) || "",                            imageSrc: post.imageUrl || "/placeholders/placeholder1.webp",                            imageAlt: post.imageAlt || post.title || ""
                        }));
                        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="entrance-slide"
            borderRadius="soft"
            contentWidth="smallMedium"
            sizing="mediumLarge"
            background="none"
            cardStyle="soft-shadow"
            primaryButtonStyle="flat"
            secondaryButtonStyle="solid"
            headingFontWeight="light"
        >
            <ReactLenis root>
                <div className="min-h-screen bg-background">
                    <NavbarStyleApple
                        brandName="Happy Paws"
                        navItems={[
                            { name: "Home", id: "hero" },
                            { name: "About", id: "about" },
                            { name: "Adopt", id: "featured" },
                            { name: "FAQ", id: "faq" },
                            { name: "Contact", id: "contact" }
                        ]}
                    />

                    {isLoading ? (
                        <div className="w-content-width mx-auto py-20 text-center">
                            <p className="text-foreground">Loading stories...</p>
                        </div>
                    ) : (
                        <TestimonialCardTwo
                            testimonials={posts}
                            animationType="slide-up"
                            title="Happy Paws Stories"
                            description="Discover heartwarming tales of rescue, care, and forever homes from our animal shelter community."
                            textboxLayout="default"
                            useInvertedBackground="noInvert"
                            tag="Blog"
                            tagIcon={PawPrint}
                        />
                    )}

                    <FooterCard
                        logoText="Happy Paws"
                        copyrightText="© 2025 Happy Paws Shelter | Helping animals find forever homes"
                        socialLinks={[
                            { icon: Facebook, href: "https://facebook.com/happypaws", ariaLabel: "Facebook" },
                            { icon: Instagram, href: "https://instagram.com/happypaws", ariaLabel: "Instagram" },
                            { icon: Twitter, href: "https://twitter.com/happypaws", ariaLabel: "Twitter" }
                        ]}
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}