"use client";

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

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: "Cosmetic Dentistry",        title: "The Art of Smile Design",        excerpt: "Discover how our digital smile design technology helps you visualize your perfect smile before treatment begins.",        imageSrc: "https://images.unsplash.com/photo-1588776694971-91b1560f9b5e?w=800&h=600&fit=crop",        imageAlt: "Smile design consultation",        authorName: "Dr. Elizabeth Foster",        authorAvatar: "https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=400&h=400&fit=crop",        date: "20 Jan 2025",        onBlogClick: () => console.log("Blog 1 clicked"),
    },
    {
        id: "2",        category: "Dental Technology",        title: "Advanced Implant Solutions",        excerpt: "Learn how modern dental implant technology restores function and beauty with natural-looking results.",        imageSrc: "https://images.unsplash.com/photo-1606811841689-23def00b0ae4?w=800&h=600&fit=crop",        imageAlt: "Dental implant technology",        authorName: "Dr. Michael Chang",        authorAvatar: "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=400&h=400&fit=crop",        date: "18 Jan 2025",        onBlogClick: () => console.log("Blog 2 clicked"),
    },
    {
        id: "3",        category: "Preventive Care",        title: "Maintaining Your Perfect Smile",        excerpt: "Expert tips on maintaining your dental health and preserving your beautiful smile for life.",        imageSrc: "https://images.unsplash.com/photo-1579154204601-01d8d844e250?w=800&h=600&fit=crop",        imageAlt: "Preventive dental care",        authorName: "Dr. Sarah Johnson",        authorAvatar: "https://images.unsplash.com/photo-1438761681033-6461ffad8d80?w=400&h=400&fit=crop",        date: "15 Jan 2025",        onBlogClick: () => console.log("Blog 3 clicked"),
    },
    {
        id: "4",        category: "Patient Stories",        title: "Smile Transformations: Real Results",        excerpt: "See how our patients' lives changed when they invested in their smiles through our personalized treatments.",        imageSrc: "https://images.unsplash.com/photo-1631217174556-e5b42bb30ac4?w=800&h=600&fit=crop",        imageAlt: "Smile transformation results",        authorName: "Dr. James Mitchell",        authorAvatar: "https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=400&h=400&fit=crop",        date: "12 Jan 2025",        onBlogClick: () => console.log("Blog 4 clicked"),
    },
];

const footerColumns: FooterColumn[] = [
    {
        title: "Services",        items: [
            { label: "Cosmetic Dentistry", href: "#services" },
            { label: "Dental Implants", href: "#services" },
            { label: "Orthodontics", href: "#services" },
        ],
    },
    {
        title: "Practice",        items: [
            { label: "About Us", href: "#about" },
            { label: "Our Team", href: "#team" },
            { label: "Contact", href: "#contact" },
        ],
    },
    {
        title: "Resources",        items: [
            { label: "Blog", href: "/blog" },
            { label: "Patient Forms", href: "#" },
            { label: "Smile Gallery", 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 || "Dental Care",                            title: post.title || "Untitled",                            excerpt: post.excerpt || post.content.slice(0, 30) || "",                            imageSrc: post.imageUrl || "https://images.unsplash.com/photo-1588776694971-91b1560f9b5e?w=800&h=600&fit=crop",                            imageAlt: post.imageAlt || post.title || "",                            authorName: post.author?.name || "Anonymous",                            authorAvatar: post.author?.avatar || "https://images.unsplash.com/photo-1494790108377-be9c29b29330?w=400&h=400&fit=crop",                            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-stagger"
            defaultTextAnimation="reveal-blur"
            borderRadius="pill"
            contentWidth="smallMedium"
            sizing="mediumLargeSizeMediumTitles"
            background="aurora"
            cardStyle="layered-gradient"
            primaryButtonStyle="primary-glow"
            secondaryButtonStyle="solid"
            headingFontWeight="light"
        >
            <ReactLenis root>
                <div className="min-h-screen bg-background">
                    <NavbarLayoutFloatingInline
                        brandName="Luxury Dental Care"
                        navItems={[
                            { name: "Home", id: "/" },
                            { name: "Services", id: "services" },
                            { name: "About", id: "about" },
                            { name: "Contact", id: "contact" }
                        ]}
                        button={{ text: "Schedule Consultation", href: "#contact" }}
                    />

                    {isLoading ? (
                        <div className="w-content-width mx-auto py-20 text-center">
                            <p className="text-foreground">Loading articles...</p>
                        </div>
                    ) : (
                        <BlogCardOne
                            blogs={posts}
                            title="Dental Care Insights"
                            description="Learn from our expert dentists about the latest in cosmetic, restorative, and preventive dental care"
                            textboxLayout="default"
                            useInvertedBackground="noInvert"
                            carouselMode="buttons"
                            animationType="slide-up"
                        />
                    )}

                    <FooterBase
                        logoText="Luxury Dental Care California"
                        copyrightText="© 2025 Luxury Dental Care | Premium Dentistry Since 2005"
                        columns={[
                            {
                                title: "Services",                                items: [
                                    { label: "Cosmetic Dentistry", href: "#services" },
                                    { label: "Dental Implants", href: "#services" },
                                    { label: "Orthodontics", href: "#services" },
                                    { label: "Restorative Care", href: "#services" }
                                ]
                            },
                            {
                                title: "Practice",                                items: [
                                    { label: "About Us", href: "#about" },
                                    { label: "Our Team", href: "#team" },
                                    { label: "Technology", href: "#features" },
                                    { label: "Contact", href: "#contact" }
                                ]
                            },
                            {
                                title: "Connect",                                items: [
                                    { label: "Instagram", href: "https://instagram.com" },
                                    { label: "Facebook", href: "https://facebook.com" },
                                    { label: "Google Reviews", href: "https://google.com" },
                                    { label: "Blog", href: "/blog" }
                                ]
                            }
                        ]}
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}
