import React, { useState, useRef, useEffect } from 'react';
import { useTranslation } from '@/hooks/useTranslation';
import { ChevronLeft, ChevronRight } from 'lucide-react';

export default function ImageGallery({ images, title }) {
    const { t } = useTranslation();
    const mainImgObj = images?.find(img => img.is_main) || images?.[0];
    const [activeImage, setActiveImage] = useState(mainImgObj ? `/storage/${mainImgObj.path}` : '/placeholder.jpg');

    // --- Scroll Logic State & Refs ---
    const scrollRef = useRef(null);
    const [showLeft, setShowLeft] = useState(false);
    const [showRight, setShowRight] = useState(false);

    const checkScroll = () => {
        if (scrollRef.current) {
            const { scrollLeft, scrollWidth, clientWidth } = scrollRef.current;
            setShowLeft(Math.abs(scrollLeft) > 0);
            setShowRight(Math.ceil(Math.abs(scrollLeft) + clientWidth) < scrollWidth - 5);
        }
    };

    useEffect(() => {
        checkScroll();
        window.addEventListener('resize', checkScroll);
        return () => window.removeEventListener('resize', checkScroll);
    }, [images]);

    const scroll = (direction) => {
        if (scrollRef.current) {
            const offset = direction === 'left' ? -150 : 150;
            const isRtl = document.documentElement.dir === 'rtl';
            const finalOffset = isRtl ? (direction === 'left' ? 150 : -150) : offset;
            
            scrollRef.current.scrollBy({ left: finalOffset, behavior: 'smooth' });
            setTimeout(checkScroll, 300);
        }
    };

    return (
        /* Removed 'flex flex-col' to stop children from stretching or pushing apart */
        <div className="lg:col-span-5 p-4 md:p-6 border-b lg:border-b-0 lg:border-r border-border/50">
            
            {/* Main Active Image - Maintains its square aspect ratio */}
            <div className="aspect-square rounded-lg overflow-hidden border border-border bg-white mb-4 flex items-center justify-center">
                <img src={activeImage} alt={title} className="w-full h-full object-contain" />
            </div>
            
            {/* Thumbnails Gallery - Removed 'mt-auto' so it sits directly under the main image */}
            {images && images.length > 1 && (
                <div className="relative group w-full">
                    
                    {/* Left Scroll Button */}
                    {showLeft && (
                        <button 
                            onClick={() => scroll('left')}
                            className="absolute left-0 top-1/2 -translate-y-1/2 z-10 w-8 h-8 rounded-full bg-background/90 border shadow-md flex items-center justify-center hover:bg-muted text-primary -ml-2 transition-all opacity-0 group-hover:opacity-100"
                        >
                            <ChevronLeft className="w-5 h-5 rtl:rotate-180" />
                        </button>
                    )}

                    {/* Scrollable Thumbnails Container */}
                    <div 
                        ref={scrollRef}
                        onScroll={checkScroll}
                        className="flex gap-2 overflow-x-auto py-1 no-scrollbar scroll-smooth relative px-1"
                    >
                        {images.map((img, idx) => {
                            const imgUrl = `/storage/${img.path}`;
                            return (
                                <button 
                                    key={idx} 
                                    onMouseEnter={() => setActiveImage(imgUrl)} 
                                    onClick={() => setActiveImage(imgUrl)}
                                    className={`shrink-0 w-16 h-16 rounded-md border-2 overflow-hidden transition-all bg-white ${
                                        activeImage === imgUrl ? 'border-primary shadow-sm' : 'border-transparent hover:border-primary/50'
                                    }`}
                                >
                                    <img 
                                        src={imgUrl} 
                                        alt={t('Thumbnail :number', { number: idx + 1 })} 
                                        className="w-full h-full object-contain p-1" 
                                    />
                                </button>
                            );
                        })}
                    </div>

                    {/* Right Scroll Button */}
                    {showRight && (
                        <button 
                            onClick={() => scroll('right')}
                            className="absolute right-0 top-1/2 -translate-y-1/2 z-10 w-8 h-8 rounded-full bg-background/90 border shadow-md flex items-center justify-center hover:bg-muted text-primary -mr-2 transition-all opacity-0 group-hover:opacity-100"
                        >
                            <ChevronRight className="w-5 h-5 rtl:rotate-180" />
                        </button>
                    )}
                </div>
            )}
        </div>
    );
}