"use client";

import { useEffect, useState } from "react";
import ReactLenis from "lenis/react";
import BlogCardEleven from '@/components/sections/blog/BlogCardEleven';
import FooterCard from '@/components/sections/footer/FooterCard';
import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import NavbarStyleApple from '@/components/navbar/NavbarStyleApple/NavbarStyleApple';
import { PawPrint } from 'lucide-react';

type BlogPost = {
    id: string;
    title: string;
    author: string;
    description: string;
    tags: string[];
    imageSrc?: string;
    imageAlt?: string;
    videoSrc?: string;
    videoAriaLabel?: string;
    onBlogClick?: () => void;
};

const defaultPosts: BlogPost[] = [
    {
        id: "1",        title: "Finding Forever Homes: Success Stories from Happy Paws",        author: "Sarah Mitchell",        description: "Heartwarming stories of rescued animals finding their perfect families through our adoption program.",        tags: ["Adoption", "Success Stories"],
        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Happy dog with new family",        onBlogClick: () => console.log("Blog 1 clicked"),
    },
    {
        id: "2",        title: "Pet Care Tips: Keeping Your Furry Friends Healthy",        author: "Dr. Michael Chen",        description: "Essential health and wellness tips from our veterinary team to ensure your pets live their best lives.",        tags: ["Health", "Tips"],
        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Veterinarian examining a cat",        onBlogClick: () => console.log("Blog 2 clicked"),
    },
    {
        id: "3",        title: "Volunteer Spotlight: Making a Difference Together",        author: "Emma Rodriguez",        description: "Meet our amazing volunteers who dedicate their time to helping animals in need find loving homes.",        tags: ["Volunteers", "Community"],
        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Volunteers playing with shelter dogs",        onBlogClick: () => console.log("Blog 3 clicked"),
    },
    {
        id: "4",        title: "Understanding Animal Behavior: A Guide for New Pet Parents",        author: "Lisa Thompson",        description: "Learn to decode your pet's behavior and build a stronger bond with your new four-legged family member.",        tags: ["Behavior", "New Owners"],
        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Dog trainer working with a puppy",        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}`;
                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()),
                            title: post.title || "Untitled",                            author: post.author?.name || "Anonymous",                            description: post.excerpt || post.content?.slice(0, 100) || "",                            tags: post.tags || ["General"],
                            imageSrc: post.imageUrl || "/placeholders/placeholder3.avif",                            imageAlt: post.imageAlt || post.title || "",                            videoSrc: post.videoUrl,
                            videoAriaLabel: post.videoAriaLabel || post.title || "",                            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="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 posts...</p>
                        </div>
                    ) : (
                        <BlogCardEleven
                            blogs={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>
    );
}