import React, { useState, useEffect } from 'react';
import { Carousel, CarouselContent, CarouselItem } from "@/Components/ui/carousel";
import { Skeleton } from '@/Components/ui/skeleton';
import { Maximize2, ChevronLeft, ChevronRight, ImageIcon } from 'lucide-react';
import { cn } from "@/lib/utils";
import { useLightbox } from '@/Components/LightboxProvider';

export default function ArticleMedia({ post, sortedImages, gallerySlides }) {
    const { openLightbox } = useLightbox(); 
    const [api, setApi] = useState(null);
    const [current, setCurrent] = useState(0);
    const [count, setCount] = useState(0);
    const [captionLoading, setCaptionLoading] = useState(false);

    useEffect(() => {
        if (!api) return;
        setCount(api.scrollSnapList().length);
        setCurrent(api.selectedScrollSnap());

        api.on("select", () => {
            setCaptionLoading(true);
            setCurrent(api.selectedScrollSnap());
            setTimeout(() => setCaptionLoading(false), 400); 
        });
    }, [api]);

    if (sortedImages.length <= 1 && !post.image_path) {
        return null; // Nothing to show
    }

    return (
        <div className="mb-8">
            {sortedImages.length > 1 ? (
                <div className="space-y-3">
                    <div className="group relative w-full rounded-2xl overflow-hidden shadow-2xl bg-black">
                        <Carousel setApi={setApi} className="w-full">
                            <CarouselContent>
                                {sortedImages.map((img, index) => (
                                    <CarouselItem key={img.id} className="relative w-full aspect-video md:aspect-[2/1]">
                                        <img 
                                            src={img.image_path} 
                                            alt={img.caption || post.title} 
                                            className="w-full h-full object-cover cursor-zoom-in"
                                            onClick={() => openLightbox(gallerySlides, index)} 
                                        />
                                        <div className="absolute top-4 right-4 bg-black/50 p-2 rounded-full text-white opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none">
                                            <Maximize2 className="w-4 h-4" />
                                        </div>
                                    </CarouselItem>
                                ))}
                            </CarouselContent>
                        </Carousel>

                        <div className="absolute bottom-4 left-4 right-4 flex items-center gap-4 z-20 pointer-events-none">
                            <button onClick={() => api?.scrollPrev()} className="pointer-events-auto h-8 w-8 rounded-full bg-white text-black flex items-center justify-center hover:bg-gray-200 transition-colors shadow-lg active:scale-95 rtl:rotate-180">
                                <ChevronLeft className="w-5 h-5" />
                            </button>
                            <div className="flex-1 flex gap-2 h-1 pointer-events-auto">
                                {Array.from({ length: count }).map((_, index) => (
                                    <button
                                        key={index}
                                        onClick={() => api?.scrollTo(index)}
                                        className={cn(
                                            "h-full flex-1 rounded-full transition-all duration-300 ease-in-out",
                                            current === index ? "bg-red-600" : "bg-white/20 hover:bg-white/40"
                                        )}
                                    />
                                ))}
                            </div>
                            <button onClick={() => api?.scrollNext()} className="pointer-events-auto h-8 w-8 rounded-full bg-white text-black flex items-center justify-center hover:bg-gray-200 transition-colors shadow-lg active:scale-95 rtl:rotate-180">
                                <ChevronRight className="w-5 h-5" />
                            </button>
                        </div>
                    </div>

                    <div className="min-h-[24px] px-1">
                        {captionLoading ? (
                            <div className="space-y-2 animate-pulse flex flex-col items-center">
                                <Skeleton className="h-4 w-3/4 rounded" />
                                <Skeleton className="h-3 w-1/2 rounded" />
                            </div>
                        ) : (
                            <div className="text-center animate-in fade-in slide-in-from-top-1 duration-300">
                                {sortedImages[current]?.caption && sortedImages[current].caption.trim() !== "" ? (
                                    <div className="flex items-center justify-center gap-2 text-sm text-muted-foreground italic">
                                        <ImageIcon className="w-4 h-4 opacity-50 shrink-0" />
                                        <span>{sortedImages[current].caption}</span>
                                    </div>
                                ) : null}
                            </div>
                        )}
                    </div>
                </div>
            ) : post.image_path && (
                <figure className="rounded-2xl overflow-hidden bg-muted border border-border shadow-lg relative group">
                    <img 
                        src={post.image_path} 
                        alt={post.title} 
                        className="w-full h-auto object-cover cursor-zoom-in"
                        onClick={() => openLightbox(gallerySlides, 0)} 
                    />
                    <div className="absolute top-4 right-4 bg-black/50 p-2 rounded-full text-white opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none">
                        <Maximize2 className="w-4 h-4" />
                    </div>
                    {post.images?.[0]?.caption && post.images[0].caption.trim() !== "" && (
                        <figcaption className="p-3 text-center text-sm text-muted-foreground bg-background/50 backdrop-blur border-t italic">
                            {post.images[0].caption}
                        </figcaption>
                    )}
                </figure>
            )}
        </div>
    );
}