"use client";

import { useEffect, useState } from "react";
import ReactLenis from "lenis/react";
import BlogCardTwo from '@/components/sections/blog/BlogCardTwo';
import FooterSimple from '@/components/sections/footer/FooterSimple';
import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import NavbarLayoutFloatingInline from '@/components/navbar/NavbarLayoutFloatingInline';
import { BookOpen } from 'lucide-react';

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 Health Tips",        excerpt: "Learn the most important health practices to keep your adopted pet happy and healthy throughout their life.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Happy healthy pet with veterinarian",        authorName: "Dr. Sarah Johnson",        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",        excerpt: "Heartwarming stories of rescued animals finding their perfect families through our adoption program.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Happy family with newly adopted pet",        authorName: "Emily Chen",        authorAvatar: "/placeholders/placeholder4.webp",        date: "18 Jan 2025",        onBlogClick: () => console.log("Blog 2 clicked"),
    },
    {
        id: "3",        category: ["Training", "Behavior"],
        title: "Training Your New Rescue Pet",        excerpt: "Expert guidance on helping your newly adopted pet adjust to their new home with positive training techniques.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Person training rescue dog",        authorName: "Mike Rodriguez",        authorAvatar: "/placeholders/placeholder3.avif",        date: "15 Jan 2025",        onBlogClick: () => console.log("Blog 3 clicked"),
    },
    {
        id: "4",        category: "Community",        title: "Volunteer Spotlight",        excerpt: "Meet our amazing volunteers who dedicate their time to helping animals find loving homes.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Volunteers caring for shelter animals",        authorName: "Lisa Thompson",        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="icon-arrow"
            defaultTextAnimation="background-highlight"
            borderRadius="soft"
            contentWidth="mediumLarge"
            sizing="largeSizeMediumTitles"
            background="floatingGradient"
            cardStyle="gradient-mesh"
            primaryButtonStyle="radial-glow"
            secondaryButtonStyle="radial-glow"
            headingFontWeight="medium"
        >
            <ReactLenis root>
                <div className="min-h-screen bg-background">
                    <NavbarLayoutFloatingInline
                        brandName="PawsAdopt"
                        navItems={[
                            { name: "Home", id: "/home" },
                            { name: "About", id: "about" },
                            { name: "Pets", id: "featured-pets" },
                            { name: "Stories", id: "testimonials" },
                            { name: "FAQ", id: "faq" }
                        ]}
                        button={{ text: "Get Started", 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="Pet Care & Adoption Stories"
                            description="Discover helpful tips, heartwarming stories, and expert advice to support you on your pet adoption journey."
                            tag="Blog"
                            tagIcon={BookOpen}
                            textboxLayout="default"
                            useInvertedBackground="noInvert"
                            animationType="slide-up"
                            carouselMode="buttons"
                        />
                    )}

                    <FooterSimple
                        columns={[
                            {
                                title: "Organization",                                items: [
                                    { label: "About Us", href: "about" },
                                    { label: "Our Mission", href: "about" },
                                    { label: "Careers", href: "#" }
                                ]
                            },
                            {
                                title: "Adoption",                                items: [
                                    { label: "Browse Pets", href: "featured-pets" },
                                    { label: "Adoption Process", href: "faq" },
                                    { label: "Success Stories", href: "testimonials" }
                                ]
                            },
                            {
                                title: "Get Involved",                                items: [
                                    { label: "Volunteer", href: "contact" },
                                    { label: "Donate", href: "contact" },
                                    { label: "Sponsor a Pet", href: "contact" }
                                ]
                            },
                            {
                                title: "Support",                                items: [
                                    { label: "FAQ", href: "faq" },
                                    { label: "Contact", href: "contact" },
                                    { label: "Pet Care Tips", href: "#" }
                                ]
                            }
                        ]}
                        bottomLeftText="© 2025 PawsAdopt Animal Shelter. All rights reserved."
                        bottomRightText="Giving animals a second chance at happiness"
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}