import React, { useEffect, useRef, useState } from "react";
import { Heart, ShoppingCart } from "lucide-react";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";

export default function ProductImageGallery({
    product,
    mainImage,
    setMainImage,
    API,
    addToCart,
    addToWishlist,
}) {
    const slideInterval = useRef(null);
    const [liked, setLiked] = useState(false);
    const [animateHeart, setAnimateHeart] = useState(false);

    // Auto-slide images every 2 seconds
    useEffect(() => {
        if (!product?.media?.length) return;

        slideInterval.current = setInterval(() => {
            setMainImage((prev) => {
                const index = product.media.findIndex((img) => `${API}${img.url}` === prev);
                const nextIndex = (index + 1) % product.media.length;
                return `${API}${product.media[nextIndex].url}`;
            });
        }, 2000);

        return () => clearInterval(slideInterval.current);
    }, [product, API, setMainImage]);

    // Reset timer when user manually selects a thumbnail
    const handleThumbnailClick = (imgUrl) => {
        clearInterval(slideInterval.current);
        setMainImage(imgUrl);

        slideInterval.current = setInterval(() => {
            setMainImage((prev) => {
                const index = product.media.findIndex((img) => `${API}${img.url}` === prev);
                const nextIndex = (index + 1) % product.media.length;
                return `${API}${product.media[nextIndex].url}`;
            });
        }, 3000);
    };

    // Handle heart (wishlist) click
    const handleHeartClick = (e) => {
        e.stopPropagation();

        const newLikedState = !liked;
        setLiked(newLikedState);
        setAnimateHeart(true);
        setTimeout(() => setAnimateHeart(false), 400);

        if (newLikedState) {
            toast.success("Added to wishlist");
            addToWishlist?.(product);
        } else {
            toast.error("Removed from wishlist");
        }
    };

    return (
        <div className="flex flex-col items-center">
            {/* MAIN IMAGE CONTAINER */}
            <div className="relative flex justify-center items-center bg-gray-50 rounded-2xl shadow-md w-full overflow-hidden">
                {/* Wishlist Heart */}
                <button
                    onClick={handleHeartClick}
                    className="absolute z-20 top-3 right-3 p-2 bg-white rounded-full shadow-md 
                     hover:scale-110 transition-all border border-gray-200"
                >
                    <Heart
                        size={20}
                        className={`transition-all duration-300 ease-out 
              ${liked ? "text-red-500" : "text-gray-600"} 
              ${animateHeart ? "scale-125" : "scale-100"}
            `}
                        fill={liked ? "red" : "none"}
                    />
                </button>

                {/* MAIN IMAGE */}
                <div className="sm:w-[400px] h-[300px] sm:h-[400px] flex justify-center items-center">
                    <img
                        src={mainImage || "/placeholder-image.png"}
                        alt={product?.name || "Product"}
                        className="max-w-[400px] max-h-[350px] object-contain transition-transform duration-700 ease-in-out hover:scale-105"
                    />
                </div>
            </div>

            {/* MOBILE THUMBNAILS */}
            <div className="flex md:hidden flex-wrap justify-center gap-3 mt-4">
                {product?.media?.map((img, index) => (
                    <img
                        key={index}
                        src={`${API}${img.url}`}
                        alt={product.name}
                        onClick={() => handleThumbnailClick(`${API}${img.url}`)}
                        className={`w-20 h-20 object-cover rounded-xl cursor-pointer border-2 transition-transform duration-300 ${mainImage === `${API}${img.url}`
                                ? "border-blue-500 scale-105"
                                : "border-gray-300 hover:scale-105"
                            }`}
                    />
                ))}
            </div>

            {/* BUTTONS */}
            <div className="flex flex-col sm:flex-row gap-4 mt-6 w-full sm:w-[500px]">
                <Button
                    onClick={() => addToCart(product)}
                    className="bg-black text-white hover:bg-gray-900 active:scale-95 transition-transform duration-150 py-4 text-base sm:text-lg rounded flex-1 flex items-center justify-center hover:scale-105"
                >
                    <ShoppingCart className="w-5 h-5 mr-2" />
                    Add to Cart
                </Button>

                <Button
                    onClick={() => addToWishlist(product)}
                    className="bg-gray-200 text-black hover:bg-gray-300 active:scale-95 transition-transform duration-150 py-4 text-base sm:text-lg rounded flex-1 flex items-center justify-center hover:scale-105"
                >
                    <ShoppingCart className="w-5 h-5 mr-2" />
                    Buy Now
                </Button>
            </div>
        </div>
    );
}
