"use client";

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

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: "Helping Abandoned Pets Find Forever Homes",        author: "Sarah Johnson",        description: "Learn about our comprehensive adoption process and how we match pets with the perfect families.",        tags: ["Adoption", "Success Stories"],
        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Happy family with their newly adopted pet",        onBlogClick: () => console.log("Blog 1 clicked"),
    },
    {
        id: "2",        title: "Volunteer Spotlight: Making a Difference",        author: "Mike Davis",        description: "Meet our amazing volunteers who dedicate their time to caring for animals in need.",        tags: ["Volunteers", "Community"],
        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Volunteer caring for shelter animals",        onBlogClick: () => console.log("Blog 2 clicked"),
    },
    {
        id: "3",        title: "Pet Care Tips for New Owners",        author: "Dr. Emily Chen",        description: "Essential advice for first-time pet owners to ensure their new companions are healthy and happy.",        tags: ["Pet Care", "Education"],
        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Veterinarian examining a pet",        onBlogClick: () => console.log("Blog 3 clicked"),
    },
    {
        id: "4",        title: "Supporting Our Mission Through Donations",        author: "Lisa Brown",        description: "Discover how your contributions help us provide medical care, food, and shelter for animals in need.",        tags: ["Donations", "Impact"],
        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Shelter facilities showing care areas",        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 || [post.category || "General"],
                            imageSrc: post.imageUrl || "/placeholders/placeholder3.avif",                            imageAlt: post.imageAlt || 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-shift"
            defaultTextAnimation="entrance-slide"
            borderRadius="sharp"
            contentWidth="small"
            sizing="largeSmallSizeMediumTitles"
            background="floatingGradient"
            cardStyle="inset"
            primaryButtonStyle="shadow"
            secondaryButtonStyle="layered"
            headingFontWeight="bold"
        >
            <ReactLenis root>
                <div className="min-h-screen bg-background">
                    <NavbarStyleApple
                        brandName="Happy Paws Shelter"
                        navItems={[
                            { name: "Home", id: "hero" },
                            { name: "Adopt", id: "featured-animals" },
                            { name: "About", id: "about" },
                            { name: "Stories", id: "testimonials" },
                            { 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="Latest News & Stories"
                            description="Stay updated with our latest rescue stories, adoption successes, and animal care tips from the Happy Paws Shelter community."
                            textboxLayout="default"
                            useInvertedBackground="noInvert"
                            tag="Blog"
                        />
                    )}

                    <FooterBaseCard
                        logoText="Happy Paws Shelter"
                        copyrightText="© 2025 Happy Paws Shelter. All rights reserved. Dedicated to animal welfare."
                        columns={[
                            {
                                title: "Quick Links",                                items: [
                                    { label: "Browse Animals", href: "#featured-animals" },
                                    { label: "Adoption Process", href: "#adoption-process" },
                                    { label: "Success Stories", href: "#testimonials" }
                                ]
                            },
                            {
                                title: "Support",                                items: [
                                    { label: "Donate", href: "#contact" },
                                    { label: "Volunteer", href: "#contact" },
                                    { label: "Partner With Us", href: "#contact" }
                                ]
                            },
                            {
                                title: "Company",                                items: [
                                    { label: "About Us", href: "#about" },
                                    { label: "Contact", href: "#contact" },
                                    { label: "Careers", href: "#contact" }
                                ]
                            },
                            {
                                title: "Legal",                                items: [
                                    { label: "Privacy Policy", href: "#" },
                                    { label: "Terms of Service", href: "#" },
                                    { label: "Accessibility", href: "#" }
                                ]
                            }
                        ]}
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}