"use client";

import { useEffect, useState } from "react";
import ReactLenis from "lenis/react";
import BlogCardTwo from '@/components/sections/blog/BlogCardTwo';
import FooterBase from '@/components/sections/footer/FooterBase';
import { ThemeProvider } from "@/providers/themeProvider/ThemeProvider";
import type { FooterColumn } from "@/components/shared/FooterColumns";
import NavbarLayoutFloatingOverlay from '@/components/navbar/NavbarLayoutFloatingOverlay/NavbarLayoutFloatingOverlay';

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: ["Culinary", "Fine Dining"],
        title: "The Art of Japanese Cuisine",        excerpt: "Discover the intricate techniques and philosophy behind our authentic Japanese culinary experience.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Traditional Japanese cuisine preparation",        authorName: "Chef Takashi",        authorAvatar: "/placeholders/placeholder3.avif",        date: "20 Jan 2025",        onBlogClick: () => console.log("Blog 1 clicked"),
    },
    {
        id: "2",        category: "Wine Pairing",        title: "Perfect Wine Pairings",        excerpt: "Learn about our curated wine selection and how each vintage complements our seasonal menu.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Wine pairing with Japanese cuisine",        authorName: "Sommelier Yuki",        authorAvatar: "/placeholders/placeholder4.webp",        date: "18 Jan 2025",        onBlogClick: () => console.log("Blog 2 clicked"),
    },
    {
        id: "3",        category: ["Experience", "Ambiance"],
        title: "Dining Experience Excellence",        excerpt: "Immerse yourself in the serene atmosphere and exceptional service that defines NISEKO.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Elegant restaurant interior",        authorName: "Manager Akiko",        authorAvatar: "/placeholders/placeholder3.avif",        date: "15 Jan 2025",        onBlogClick: () => console.log("Blog 3 clicked"),
    },
    {
        id: "4",        category: "Seasonal",        title: "Seasonal Menu Highlights",        excerpt: "Explore our seasonal offerings featuring the freshest ingredients and traditional techniques.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Seasonal Japanese dishes",        authorName: "Chef Hiroshi",        authorAvatar: "/placeholders/placeholder4.webp",        date: "12 Jan 2025",        onBlogClick: () => console.log("Blog 4 clicked"),
    },
];

const footerColumns: FooterColumn[] = [
    {
        title: "Restaurant",        items: [
            { label: "Menu", href: "#menu" },
            { label: "Reservations", href: "#contact" },
            { label: "Private Dining", href: "#contact" },
            { label: "Wine Selection", href: "#features" }
        ]
    },
    {
        title: "Contact",        items: [
            { label: "Email", href: "mailto:info@nisekofine.com" },
            { label: "Phone", href: "tel:+81-90-XXXX-XXXX" },
            { label: "Location", href: "#" },
            { label: "Hours", href: "#" }
        ]
    },
    {
        title: "Company",        items: [
            { label: "About Us", href: "#about" },
            { label: "Our Chef", href: "#features" },
            { label: "Careers", href: "#" },
            { label: "Press", href: "#" }
        ]
    }
];

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="bounce-effect"
            defaultTextAnimation="entrance-slide"
            borderRadius="sharp"
            contentWidth="smallMedium"
            sizing="mediumLargeSizeLargeTitles"
            background="floatingGradient"
            cardStyle="solid"
            primaryButtonStyle="gradient"
            secondaryButtonStyle="glass"
            headingFontWeight="light"
        >
            <ReactLenis root>
                <div className="min-h-screen bg-background">
                    <NavbarLayoutFloatingOverlay
                        brandName="NISEKO"
                        navItems={[
                            { name: "Home", id: "/home" },
                            { name: "Menu", id: "menu" },
                            { name: "Experience", id: "experience" },
                            { name: "About", id: "about" },
                            { name: "Reviews", id: "reviews" },
                            { name: "Contact", id: "contact" }
                        ]}
                        button={{ text: "Reserve", 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="Culinary Stories & Insights"
                            description="Discover the artistry behind our cuisine, wine pairings, and exceptional dining experiences at NISEKO"
                            textboxLayout="default"
                            useInvertedBackground="noInvert"
                            animationType="slide-up"
                            carouselMode="buttons"
                            tag="Blog"
                        />
                    )}

                    <FooterBase
                        logoText="NISEKO"
                        copyrightText="© 2025 Niseko Fine Dining. All rights reserved."
                        columns={footerColumns}
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}