"use client";

import { useEffect, useState } from "react";
import ReactLenis from "lenis/react";
import BlogCardTwo from '@/components/sections/blog/BlogCardTwo';
import FooterCard from '@/components/sections/footer/FooterCard';
import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import NavbarStyleMinimal from '@/components/navbar/NavbarStyleMinimal';
import { Instagram, Facebook, Mail } 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: ["Nail Art", "Design"],
        title: "Latest Nail Art Trends",        excerpt: "Discover the hottest nail art trends for 2025 and how to achieve them at home or in our salon.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Beautiful nail art designs",        authorName: "Sarah Chen",        authorAvatar: "/placeholders/placeholder3.avif",        date: "20 Jan 2025",        onBlogClick: () => console.log("Blog 1 clicked"),
    },
    {
        id: "2",        category: "Beauty Tips",        title: "Nail Care Essentials",        excerpt: "Learn the essential steps for maintaining healthy, beautiful nails between salon visits.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Nail care products and tools",        authorName: "Emma Wilson",        authorAvatar: "/placeholders/placeholder4.webp",        date: "18 Jan 2025",        onBlogClick: () => console.log("Blog 2 clicked"),
    },
    {
        id: "3",        category: ["Gel Nails", "Techniques"],
        title: "Gel Nail Longevity Tips",        excerpt: "Discover professional secrets to make your gel manicure last longer and look salon-fresh.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Perfect gel nails",        authorName: "Lisa Rodriguez",        authorAvatar: "/placeholders/placeholder3.avif",        date: "15 Jan 2025",        onBlogClick: () => console.log("Blog 3 clicked"),
    },
    {
        id: "4",        category: "Seasonal Trends",        title: "Spring Nail Color Palette",        excerpt: "Explore the perfect spring nail colors that will complement your wardrobe and mood.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Spring nail color swatches",        authorName: "Jessica Park",        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="shift-hover"
            defaultTextAnimation="background-highlight"
            borderRadius="rounded"
            contentWidth="compact"
            sizing="medium"
            background="floatingGradient"
            cardStyle="gradient-radial"
            primaryButtonStyle="double-inset"
            secondaryButtonStyle="radial-glow"
            headingFontWeight="normal"
        >
            <ReactLenis root>
                <div className="min-h-screen bg-background">
                    <NavbarStyleMinimal
                        brandName="Luxe Nails Sydney"
                        button={{
                            text: "Book Appointment",                            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="Beauty & Nail Care Insights"
                            description="Discover expert tips, trends, and techniques from our professional nail artists"
                            textboxLayout="default"
                            useInvertedBackground="noInvert"
                            carouselMode="buttons"
                            animationType="slide-up"
                            tag="Blog"
                        />
                    )}

                    <FooterCard
                        logoText="Luxe Nails"
                        copyrightText="© 2025 Luxe Nails Sydney. All rights reserved."
                        socialLinks={[
                            {
                                icon: Instagram,
                                href: "https://instagram.com",                                ariaLabel: "Instagram"
                            },
                            {
                                icon: Facebook,
                                href: "https://facebook.com",                                ariaLabel: "Facebook"
                            },
                            {
                                icon: Mail,
                                href: "mailto:hello@luxenailssydney.com",                                ariaLabel: "Email"
                            }
                        ]}
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}