"use client";

import { useEffect, useState } from "react";
import ReactLenis from "lenis/react";
import BlogCardTwo from '@/components/sections/blog/BlogCardTwo';
import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import NavbarLayoutFloatingOverlay from '@/components/navbar/NavbarLayoutFloatingOverlay/NavbarLayoutFloatingOverlay';
import FooterBaseReveal from '@/components/sections/footer/FooterBaseReveal';

type BlogPost = {
    id: string;
    tags: string[];
    title: string;
    excerpt: string;
    imageSrc: string;
    imageAlt?: string;
    authorName: string;
    date: string;
    onBlogClick?: () => void;
};

const defaultPosts: BlogPost[] = [
    {
        id: "1",        tags: ["Pet Care", "Health"],
        title: "Essential Pet Health Tips",        excerpt: "Learn the most important health practices to keep your furry friends happy and healthy.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Pet health care essentials",        authorName: "Dr. Sarah Wilson",        date: "20 Jan 2025",        onBlogClick: () => console.log("Blog 1 clicked"),
    },
    {
        id: "2",        tags: ["Adoption", "Success Stories"],
        title: "Finding Forever Homes",        excerpt: "Heartwarming stories of successful pet adoptions and the joy they bring to families.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Happy adopted pets with families",        authorName: "Maria Rodriguez",        date: "18 Jan 2025",        onBlogClick: () => console.log("Blog 2 clicked"),
    },
    {
        id: "3",        tags: ["Training", "Behavior"],
        title: "Positive Training Methods",        excerpt: "Discover effective and humane training techniques that strengthen the bond with your pet.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Pet training session",        authorName: "John Thompson",        date: "15 Jan 2025",        onBlogClick: () => console.log("Blog 3 clicked"),
    },
    {
        id: "4",        tags: ["Nutrition", "Wellness"],
        title: "Nutritional Needs by Age",        excerpt: "Understanding how your pet's dietary requirements change throughout their life stages.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Pet nutrition guide",        authorName: "Dr. Emily Chen",        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}`;
                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()),
                            tags: post.tags || [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",                            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="hover-bubble"
            defaultTextAnimation="entrance-slide"
            borderRadius="rounded"
            contentWidth="medium"
            sizing="mediumLargeSizeMediumTitles"
            background="aurora"
            cardStyle="layered-gradient"
            primaryButtonStyle="shadow"
            secondaryButtonStyle="solid"
            headingFontWeight="bold"
        >
            <ReactLenis root>
                <div className="min-h-screen bg-background">
                    <NavbarLayoutFloatingOverlay
                        brandName="Pawsitive Haven"
                        navItems={[
                            { name: "Home", id: "hero" },
                            { name: "About Us", id: "about" },
                            { name: "Adopt Now", id: "featured-pets" },
                            { name: "Services", id: "services" },
                            { name: "Stories", id: "testimonials" }
                        ]}
                        button={{ text: "Donate", href: "#contact" }}
                    />

                    {isLoading ? (
                        <div className="w-content-width mx-auto py-20 text-center">
                            <p className="text-foreground">Loading posts...</p>
                        </div>
                    ) : (
                        <BlogCardTwo
                            blogs={posts}
                            title="Pawsitive Stories & Insights"
                            description="Discover helpful tips, heartwarming stories, and expert advice from our team of animal lovers and veterinary professionals."
                            textboxLayout="default"
                            useInvertedBackground="noInvert"
                            animationType="slide-up"
                            carouselMode="buttons"
                            tag="Blog"
                        />
                    )}

                    <FooterBaseReveal
                        copyrightText="© 2025 Pawsitive Haven. All rights reserved. Every animal deserves a chance."
                        columns={[
                            {
                                title: "Adoption",                                items: [
                                    { label: "Browse Pets", href: "#featured-pets" },
                                    { label: "Adoption Process", href: "#" },
                                    { label: "Frequently Asked", href: "#" }
                                ]
                            },
                            {
                                title: "About",                                items: [
                                    { label: "Our Mission", href: "#about" },
                                    { label: "Our Team", href: "#" },
                                    { label: "Contact Us", href: "#contact" }
                                ]
                            },
                            {
                                title: "Support",                                items: [
                                    { label: "Donate", href: "#contact" },
                                    { label: "Volunteer", href: "#" },
                                    { label: "Privacy Policy", href: "#" }
                                ]
                            }
                        ]}
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}