"use client";

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

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

const defaultPosts: BlogPost[] = [
    {
        id: "1",        category: ["Pet Care", "Health"],
        title: "Essential Pet Care Tips for New Adopters",        excerpt: "Learn the fundamentals of caring for your newly adopted companion, from nutrition to health checkups.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Happy dog with new family",        authorName: "Dr. Sarah Mitchell",        authorAvatar: "/placeholders/placeholder3.avif",        date: "20 Jan 2025",        onBlogClick: () => console.log("Blog 1 clicked"),
    },
    {
        id: "2",        category: "Adoption Stories",        title: "From Shelter to Forever Home: Max's Journey",        excerpt: "Follow the heartwarming story of Max, a rescue dog who found his perfect match after months of waiting.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Max the rescue dog with his new family",        authorName: "Emma Rodriguez",        authorAvatar: "/placeholders/placeholder4.webp",        date: "18 Jan 2025",        onBlogClick: () => console.log("Blog 2 clicked"),
    },
    {
        id: "3",        category: ["Training", "Behavior"],
        title: "Positive Reinforcement Training Methods",        excerpt: "Discover effective, compassionate training techniques that strengthen the bond between you and your pet.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Training session with dog",        authorName: "Mark Thompson",        authorAvatar: "/placeholders/placeholder3.avif",        date: "15 Jan 2025",        onBlogClick: () => console.log("Blog 3 clicked"),
    },
    {
        id: "4",        category: "Volunteering",        title: "How to Make a Difference at Happy Paws",        excerpt: "Explore the various ways you can volunteer and help save more lives in our community.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Volunteer walking dogs at shelter",        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}`;
                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="icon-arrow"
            defaultTextAnimation="reveal-blur"
            borderRadius="soft"
            contentWidth="small"
            sizing="mediumSizeLargeTitles"
            background="floatingGradient"
            cardStyle="inset"
            primaryButtonStyle="radial-glow"
            secondaryButtonStyle="glass"
            headingFontWeight="medium"
        >
            <ReactLenis root>
                <div className="min-h-screen bg-background">
                    <NavbarStyleMinimal
                        brandName="Happy Paws Shelter"
                        button={{
                            text: "Adopt Today",                            href: "#hero"
                        }}
                    />

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

                    <FooterMedia
                        imageSrc="asset://footer-media"
                        imageAlt="Happy Paws Shelter community"
                        logoText="Happy Paws Shelter"
                        copyrightText="© 2025 Happy Paws Shelter. All rights reserved. Together we save lives."
                        columns={[
                            {
                                title: "About",                                items: [
                                    { label: "Our Story", href: "#about" },
                                    { label: "Team", href: "#team" },
                                    { label: "Careers", href: "#careers" },
                                    { label: "Impact", href: "#impact" }
                                ]
                            },
                            {
                                title: "Get Involved",                                items: [
                                    { label: "Adopt", href: "#featured-pets" },
                                    { label: "Foster", href: "#help" },
                                    { label: "Volunteer", href: "#help" },
                                    { label: "Donate", href: "#help" }
                                ]
                            },
                            {
                                title: "Contact",                                items: [
                                    { label: "Location", href: "https://maps.google.com" },
                                    { label: "Hours", href: "#contact" },
                                    { label: "Email", href: "mailto:info@happypaws.org" },
                                    { label: "Phone", href: "tel:+1234567890" }
                                ]
                            }
                        ]}
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}