'use client';

import { motion } from 'framer-motion';
import Image from 'next/image';
import Link from 'next/link';
import { BlogPostProps } from './BlogPost';
import ArrowRightIcon from './icons/ArrowRightIcon';
import { useEffect, useState } from 'react';
import { client } from '@/sanity/client';
import { defineQuery, SanityDocument } from "next-sanity";

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,
  }[0...3] | order(_createdAt desc)`);

export default function RecentBlog() {

    const [posts, setPosts] = useState<SanityDocument[]>([]);
    const [isLoading, setIsLoading] = useState(true);

    // Initial load
    useEffect(() => {
        let mounted = true;
        const controller = new AbortController();

        async function fetchPosts() {
            try {
                const data = await client.fetch(
                    BLOG_POSTS_QUERY,
                    {},
                    { signal: controller.signal }
                );

                if (mounted) {
                    setPosts(data || []);
                    setIsLoading(false);
                }
            } catch (err) {
                if ((err as unknown as Error).name === 'AbortError') {
                    return; // Ignore abort errors
                }
                console.error('Error fetching blog posts:', err);
                if (mounted) {
                    setIsLoading(false);
                }
            }
        }

        fetchPosts();

        return () => {
            mounted = false;
            controller.abort();
        };
    }, []);

    // Show loading state
    if (isLoading) {
        return (
            <section id="blog" className="min-h-screen">
                <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>
            </section>
        );
    }

    // 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'
        })
    }));

    const featuredPost = formattedPosts[0];

    return (
        <section id="blog" className="py-20">
            <div className="container mx-auto max-w-[1200px] px-4">
                <motion.h2
                    initial={{ opacity: 0, y: 20 }}
                    whileInView={{ opacity: 1, y: 0 }}
                    transition={{ duration: 0.8 }}
                    className="text-coral font-script text-4xl md:text-5xl text-center mb-12"
                >
                    Recent Blog
                </motion.h2>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-12">
                    {/* Left column - Blog posts */}
                    <div className="space-y-8 md:border-r border-[#454545]/40 order-2 md:order-1">
                        {posts.map((post, index) => (
                            <div key={index}>
                                <motion.div
                                    initial={{ opacity: 0, y: 20 }}
                                    whileInView={{ opacity: 1, y: 0 }}
                                    transition={{ duration: 0.5, delay: index * 0.1 }}
                                    className="space-y-4 pr-8"
                                >
                                    <h3 className="text-xl font-normal">{post.title}</h3>
                                    <p className="text-body/80 font-light leading-relaxed">
                                        {post.excerpt}
                                    </p>
                                    <Link href={`/blog/${post.slug}`} className="inline-block">
                                        <button className="p-0 uppercase font-normal hover:text-coral text-sm">
                                            READ MORE
                                        </button>
                                    </Link>
                                </motion.div>
                                {index !== posts.length - 1 && <div className="border-b border-[#a1a1a1] py-3 w-full mx-auto self-center"></div>}
                            </div>
                        ))}
                    </div>

                    {/* Right column - Featured image */}
                    <motion.div
                        initial={{ opacity: 0, x: 20 }}
                        whileInView={{ opacity: 1, x: 0 }}
                        transition={{ duration: 0.8 }}
                        className="relative order-1 md:order-2"
                    >
                        <div className="relative h-[300px] w-full rounded-lg overflow-hidden">
                            <Image
                                src={featuredPost.image}
                                alt={featuredPost.title}
                                fill
                                className="object-cover"
                            />
                        </div>
                        <div className="flex flex-col ">
                            <h3 className="text-xl font-normal my-4">
                                {featuredPost.title}
                            </h3>
                            <p className="text-body/80 font-light mb-4">
                                {featuredPost.excerpt}
                            </p>
                            <Link href={`/blog/${featuredPost.slug}`} className="inline-block w-full">
                                <button className="p-0 uppercase font-normal hover:text-coral text-sm flex items-center gap-2 justify-end w-full">
                                    READ MORE <ArrowRightIcon className="w-6 h-6 ml-2 rounded-full border border-[#454545] " />
                                </button>
                            </Link>
                        </div>
                    </motion.div>
                </div>
            </div>
        </section>
    );
} 