"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 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: ["Web Development", "Programming"],
        title: "Modern JavaScript Frameworks",        excerpt: "Explore the latest JavaScript frameworks and their impact on web development.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Modern JavaScript development",        authorName: "Alex Thompson",        authorAvatar: "/placeholders/placeholder3.avif",        date: "20 Jan 2025",        onBlogClick: () => console.log("Blog 1 clicked"),
    },
    {
        id: "2",        category: "Python Programming",        title: "Python for Data Science",        excerpt: "Learn how Python has become the go-to language for data science and machine learning.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Python programming workspace",        authorName: "Sarah Chen",        authorAvatar: "/placeholders/placeholder4.webp",        date: "18 Jan 2025",        onBlogClick: () => console.log("Blog 2 clicked"),
    },
    {
        id: "3",        category: ["Data Science", "Analytics"],
        title: "Big Data Analytics Trends",        excerpt: "Discover the latest trends in big data analytics and how they're shaping businesses.",        imageSrc: "/placeholders/placeholder3.avif",        imageAlt: "Data analytics dashboard",        authorName: "Michael Rodriguez",        authorAvatar: "/placeholders/placeholder3.avif",        date: "15 Jan 2025",        onBlogClick: () => console.log("Blog 3 clicked"),
    },
    {
        id: "4",        category: "Cybersecurity",        title: "Cybersecurity Best Practices 2025",        excerpt: "Essential cybersecurity practices every developer and organization should follow.",        imageSrc: "/placeholders/placeholder4.webp",        imageAlt: "Cybersecurity concept",        authorName: "Emma Wilson",        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="slide-background"
            defaultTextAnimation="reveal-blur"
            borderRadius="pill"
            contentWidth="compact"
            sizing="mediumSizeLargeTitles"
            background="none"
            cardStyle="glass-depth"
            primaryButtonStyle="inset-glow"
            secondaryButtonStyle="layered"
            headingFontWeight="extrabold"
        >
            <ReactLenis root>
                <div className="min-h-screen bg-background">
                    <NavbarLayoutFloatingOverlay
                        brandName="TechAcademy"
                        navItems={[
                            { name: "Home", id: "/" },
                            { name: "Courses", id: "courses" },
                            { name: "About", id: "about" },
                            { name: "Contact", id: "contact" }
                        ]}
                        button={{ text: "Enroll Now", 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="Latest Tech Insights"
                            description="Stay updated with the latest trends, tutorials, and insights from the world of technology and programming"
                            textboxLayout="default"
                            useInvertedBackground="noInvert"
                            animationType="slide-up"
                            carouselMode="buttons"
                            tag="Blog"
                        />
                    )}

                    <FooterMedia
                        imageSrc="https://img.b2bpic.net/free-photo/html-css-collage-concept-with-person_23-2150061986.jpg"
                        imageAlt="Graduation and success celebration"
                        logoText="TechAcademy"
                        copyrightText="© 2025 TechAcademy. All rights reserved."
                        columns={[
                            {
                                title: "Courses",                                items: [
                                    { label: "Web Development", href: "/courses" },
                                    { label: "Python Programming", href: "/courses" },
                                    { label: "Data Science", href: "/courses" },
                                    { label: "Cybersecurity", href: "/courses" }
                                ]
                            },
                            {
                                title: "Company",                                items: [
                                    { label: "About Us", href: "/about" },
                                    { label: "Our Team", href: "/about" },
                                    { label: "Careers", href: "#" },
                                    { label: "Blog", href: "#" }
                                ]
                            },
                            {
                                title: "Support",                                items: [
                                    { label: "Contact Us", href: "/contact" },
                                    { label: "FAQ", href: "#faq" },
                                    { label: "Privacy Policy", href: "#" },
                                    { label: "Terms of Service", href: "#" }
                                ]
                            }
                        ]}
                    />
                </div>
            </ReactLenis>
        </ThemeProvider>
    );
}