"use client";

import { useEffect, useState } from "react";
import ReactLenis from "lenis/react";
import BlogCardThree from '@/components/sections/blog/BlogCardThree';
import FooterCard from '@/components/sections/footer/FooterCard';
import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import NavbarStyleFullscreen from '@/components/navbar/NavbarStyleFullscreen/NavbarStyleFullscreen';
import { Facebook, Instagram, Heart } from 'lucide-react';

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: "Animal Care",        title: "Preparing Your Home for a New Pet",        excerpt: "Essential tips to create a safe and welcoming environment for your new furry family member.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Pet preparation checklist",        authorName: "Sarah Wilson",        authorAvatar: "/placeholders/placeholder3.avif",        date: "20 Jan 2025",        onBlogClick: () => console.log("Blog 1 clicked"),
    },
    {
        id: "2",        category: "Adoption Stories",        title: "Luna's Journey to Her Forever Home",        excerpt: "Follow the heartwarming story of Luna, from rescue to finding her perfect family.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Luna the rescue dog",        authorName: "Mike Johnson",        authorAvatar: "/placeholders/placeholder4.webp",        date: "18 Jan 2025",        onBlogClick: () => console.log("Blog 2 clicked"),
    },
    {
        id: "3",        category: "Health Tips",        title: "Winter Pet Care Essentials",        excerpt: "Keep your pets healthy and comfortable during the colder months with these expert tips.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Pet winter care guide",        authorName: "Dr. Emma Martinez",        authorAvatar: "/placeholders/placeholder3.avif",        date: "15 Jan 2025",        onBlogClick: () => console.log("Blog 3 clicked"),
    },
    {
        id: "4",        category: "Community",        title: "Volunteer Spotlight: Meet Our Heroes",        excerpt: "Get to know the amazing volunteers who make our animal shelter possible.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Volunteer team photo",        authorName: "Lisa Chen",        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}?status=published`;
                const response = await fetch(url, {
                    method: "GET",                    headers: {
                        "Content-Type": "application/json"},
                });

                if (response.ok) {
                    const resp = await response.json();
                    const data = resp.data;
                    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="soft"
            contentWidth="mediumSmall"
            sizing="largeSizeMediumTitles"
            background="none"
            cardStyle="gradient-bordered"
            primaryButtonStyle="shadow"
            secondaryButtonStyle="radial-glow"
            headingFontWeight="bold"
        >
            <ReactLenis root>
                <div className="min-h-screen bg-background">
                    <NavbarStyleFullscreen
                        navItems={[
                            { name: "Home", id: "/" },
                            { name: "About", id: "about" },
                            { name: "Adoptable Pets", id: "pets" },
                            { name: "How to Adopt", id: "adopt" },
                            { name: "Support Us", id: "support" }
                        ]}
                        brandName="Happy Paws Shelter"
                        bottomLeftText="Rescue & Rehabilitation"
                        bottomRightText="hello@happypawsshelter.org"
                    />

                    {isLoading ? (
                        <div className="w-content-width mx-auto py-20 text-center">
                            <p className="text-foreground">Loading posts...</p>
                        </div>
                    ) : (
                        <BlogCardThree
                            blogs={posts}
                            title="Stories from Happy Paws"
                            description="Discover heartwarming stories, expert advice, and updates from our animal shelter community"
                            tag="Blog"
                            textboxLayout="default"
                            useInvertedBackground="noInvert"
                            animationType="slide-up"
                            carouselMode="buttons"
                            uniformGridCustomHeightClasses="min-h-[600px]"
                        />
                    )}

                    <FooterCard
                        logoText="Happy Paws"
                        copyrightText="© 2025 Happy Paws Animal Shelter. All animals deserve love and care."
                        socialLinks={[
                            {
                                icon: Facebook,
                                href: "https://facebook.com/happypawsshelter",                                ariaLabel: "Facebook"
                            },
                            {
                                icon: Instagram,
                                href: "https://instagram.com/happypawsshelter",                                ariaLabel: "Instagram"
                            },
                            {
                                icon: Heart,
                                href: "https://donate.happypawsshelter.org",                                ariaLabel: "Donate"
                            }
                        ]}
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}