'use client'

import { defineQuery, SanityDocument } from "next-sanity";
import { client } from "@/sanity/client";
import FeaturedBlog from '../components/FeaturedBlog';
import RecentBlogSection from '../components/RecentBlogSection';
import SubscribeSection from '../components/SubscribeSection';
import Navbar from "../components/Navbar";
import { useEffect, useState } from "react";
import { BlogPostProps } from "../components/BlogPost";

// Modify the query to accept a start parameter
const BLOG_POSTS_QUERY = defineQuery(`*[_type == "blogPost"] {
  title,
  excerpt,
  "slug": slug.current,
  "image": mainImage.asset->url,
  "author": author->name,
  "authorImage": author->image.asset->url,
  _createdAt,
}[$start...$end] | order(_createdAt desc)`);

export default function BlogPage() {
    const [posts, setPosts] = useState<SanityDocument[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [isLoadingMore, setIsLoadingMore] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [page, setPage] = useState(1);
    const [hasMore, setHasMore] = useState(true);
    const postsPerPage = 3;

    // Function to fetch posts with pagination
    async function fetchPosts(start: number, end: number, append: boolean = false) {
        try {
            setIsLoadingMore(append);
            const data = await client.fetch(BLOG_POSTS_QUERY, { start, end });

            if (append) {
                setPosts(prevPosts => [...prevPosts, ...data]);
            } else {
                setPosts(data || []);
            }

            // Check if we have more posts to load
            setHasMore(data.length === postsPerPage);
        } catch (err) {
            console.error('Error fetching blog posts:', err);
            setError('Failed to load blog posts');
        } finally {
            setIsLoading(false);
            setIsLoadingMore(false);
        }
    }

    // Initial load
    useEffect(() => {
        fetchPosts(0, postsPerPage);
    }, []);

    // Load more function
    const loadMore = () => {
        const nextPage = page + 1;
        const start = page * postsPerPage;
        const end = start + postsPerPage;

        setPage(nextPage);
        fetchPosts(start, end, true);
    };

    // Show loading state
    if (isLoading) {
        return (
            <main className="min-h-screen">
                <Navbar topPlacement={true} />
                <div className="container md:max-w-[1200px] mx-auto px-4 py-12 mt-40">
                    <h2 className="text-2xl font-medium">Loading blog posts...</h2>
                </div>
                <SubscribeSection />
            </main>
        );
    }

    // Show error state
    if (error) {
        return (
            <main>
                <Navbar topPlacement={true} />
                <div className="container md:max-w-[1200px] mx-auto px-4 py-12">
                    <h2 className="text-2xl font-medium">{error}</h2>
                </div>
                <SubscribeSection />
            </main>
        );
    }

    // Handle no posts found
    if (!posts || posts.length === 0) {
        return (
            <main>
                <Navbar topPlacement={true} />
                <div className="container md:max-w-[1200px] mx-auto px-4 py-12">
                    <h2 className="text-2xl font-medium">No blog posts found</h2>
                </div>
                <SubscribeSection />
            </main>
        );
    }

    // Format the posts to match the BlogPost component props
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const formattedPosts: BlogPostProps[] = posts.map((post: any) => ({
        ...post,
        date: new Date(post._createdAt).toLocaleDateString('en-US', {
            day: 'numeric',
            month: 'short',
            year: 'numeric'
        })
    }));

    // Use the first post as featured only on the first page
    const featuredPost = formattedPosts[0];
    const recentPosts = formattedPosts.slice(1);

    return (
        <main>
            <Navbar topPlacement={true} />
            <div className="container md:max-w-[1200px] mx-auto px-4">
                {featuredPost && <FeaturedBlog {...featuredPost} />}
                <RecentBlogSection blogPosts={recentPosts} loadMoreButton={loadMore} loadMore={hasMore} isLoadingMore={isLoadingMore} />

                {/* Load More Button */}
                {/* {hasMore && (
                    <div className="text-center py-8">
                        <button
                            onClick={loadMore}
                            disabled={isLoadingMore}
                            className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:bg-gray-400"
                        >
                            {isLoadingMore ? 'Loading...' : 'Load More Posts'}
                        </button>
                    </div>
                )} */}
            </div>
            <SubscribeSection />
        </main>
    );
}