"use client";

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

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

const defaultPosts: BlogPost[] = [
    {
        id: "1",        category: "Adoption Success",        title: "Max finds his forever home",        excerpt: "A heartwarming story of how Max, a rescue dog, found the perfect family and transformed their lives.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Happy dog with new family",        authorName: "Sarah Williams",        authorAvatar: "/placeholders/placeholder3.avif",        date: "20 Jan 2025",        onBlogClick: () => console.log("Blog 1 clicked"),
    },
    {
        id: "2",        category: "Pet Care",        title: "Essential tips for new pet owners",        excerpt: "Everything you need to know about caring for your newly adopted companion and ensuring their wellbeing.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Pet care essentials",        authorName: "Dr. Michael Chen",        authorAvatar: "/placeholders/placeholder4.webp",        date: "18 Jan 2025",        onBlogClick: () => console.log("Blog 2 clicked"),
    },
    {
        id: "3",        category: "Volunteer Stories",        title: "Making a difference one paw at a time",        excerpt: "Meet our amazing volunteers and discover how they're helping homeless animals find loving families.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Volunteers with animals",        authorName: "Emily Rodriguez",        authorAvatar: "/placeholders/placeholder3.avif",        date: "15 Jan 2025",        onBlogClick: () => console.log("Blog 3 clicked"),
    },
    {
        id: "4",        category: "Shelter Updates",        title: "New facilities and expanded programs",        excerpt: "Exciting updates about our shelter expansion and new programs designed to help more animals in need.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "New shelter facilities",        authorName: "Happy Paws Team",        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}`;
                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()),
                            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 || "Anonymous",                            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="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>
                    ) : (
                        <BlogCardOne
                            blogs={posts}
                            title="Animal Stories & Updates"
                            description="Discover heartwarming adoption stories, expert pet care advice, and the latest news from Happy Paws Shelter"
                            textboxLayout="default"
                            useInvertedBackground="noInvert"
                            carouselMode="buttons"
                            animationType="slide-up"
                            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>
    );
}