import React, { useRef, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Navigation, Pagination, Autoplay, Thumbs, Keyboard, EffectFade } from 'swiper/modules';
import { FaChevronLeft, FaChevronRight, FaStar, FaShoppingCart, FaSearchPlus, FaTimes } from 'react-icons/fa';
import 'swiper/css';
import 'swiper/css/navigation';
import 'swiper/css/pagination';
import 'swiper/css/effect-fade';
import 'swiper/css/thumbs';

// Define animation variants
const itemVariants = {
  hidden: { y: 20, opacity: 0 },
  visible: {
    y: 0,
    opacity: 1,
    transition: {
      type: "spring",
      stiffness: 300,
      damping: 20
    }
  }
};

const ProductCard = ({ product, onProductClick }) => {
  const thumbsSwiper = useRef(null);
  const [isZoomed, setIsZoomed] = useState(false);
  const [currentImageIndex, setCurrentImageIndex] = useState(0);
  
  // Create a unique ID for this product card to ensure Swiper instances don't interfere
  const cardId = `product-card-${product.id || Math.random().toString(36).substr(2, 9)}`;
  
  const imageUrls = product.image_urls || [];
  const allImages = [...imageUrls];

  const handleImageClick = () => {
    setIsZoomed(true);
  };

  const closeZoom = () => {
    setIsZoomed(false);
  };

  return (
    <>
      <motion.div 
        className="relative group"
        variants={itemVariants}
        whileHover={{
          y: -10,
          transition: {
            type: "spring",
            stiffness: 300,
            damping: 15
          }
        }}
      >
        {/* Main card */}
        <div className="relative bg-white rounded-xl shadow-md overflow-hidden border border-gray-100 transition-all duration-300 group-hover:shadow-xl">
          {/* Product Image */}
          <div className="relative h-48 overflow-hidden">
            {allImages.length > 1 ? (
              <div className="relative h-full">
                <Swiper
                  key={cardId} // Key prop ensures Swiper is re-created for each product
                  modules={[Navigation, Pagination, Autoplay, Thumbs, Keyboard, EffectFade]}
                  navigation={{
                    nextEl: `.swiper-button-next-custom-${cardId}`,
                    prevEl: `.swiper-button-prev-custom-${cardId}`,
                  }}
                  pagination={{
                    clickable: true,
                    dynamicBullets: true,
                    renderBullet: (index, className) => {
                      return `<span class="${className}"></span>`;
                    }
                  }}
                  autoplay={{
                    delay: 3000,
                    disableOnInteraction: false,
                    pauseOnMouseEnter: true
                  }}
                  effect="fade"
                  fadeEffect={{ crossFade: true }}
                  thumbs={{ swiper: thumbsSwiper.current && !thumbsSwiper.current.destroyed ? thumbsSwiper.current : null }}
                  keyboard={{
                    enabled: true,
                    onlyInViewport: true,
                  }}
                  loop={true}
                  onSlideChange={(swiper) => setCurrentImageIndex(swiper.realIndex)}
                  className="h-full"
                  style={{
                    '--swiper-pagination-color': '#10b981',
                    '--swiper-pagination-bullet-inactive-color': '#d1d5db',
                    '--swiper-pagination-bullet-inactive-opacity': '0.5',
                    '--swiper-pagination-bullet-size': '8px',
                    '--swiper-pagination-bullet-horizontal-gap': '4px'
                  }}
                >
                  {allImages.map((image, index) => (
                    <SwiperSlide key={`${cardId}-${index}`}>
                      <div className="relative h-full overflow-hidden">
                        <img 
                          src={image} 
                          alt={product.name} 
                          className="w-full h-full object-cover transition-transform duration-700 group-hover:scale-105 cursor-pointer"
                          loading="lazy"
                          onClick={handleImageClick}
                        />
                        <div className="absolute inset-0 bg-gradient-to-t from-black/5 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
                      </div>
                    </SwiperSlide>
                  ))}
                </Swiper>
                
                {/* Custom Navigation Buttons */}
                <button className={`swiper-button-prev-custom swiper-button-prev-custom-${cardId} absolute left-2 top-1/2 -translate-y-1/2 w-8 h-8 bg-white/80 backdrop-blur-sm rounded-full shadow-md flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all duration-300 z-10 hover:bg-white hover:scale-110`}>
                  <FaChevronLeft className="text-gray-700 text-sm" />
                </button>
                <button className={`swiper-button-next-custom swiper-button-next-custom-${cardId} absolute right-2 top-1/2 -translate-y-1/2 w-8 h-8 bg-white/80 backdrop-blur-sm rounded-full shadow-md flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all duration-300 z-10 hover:bg-white hover:scale-110`}>
                  <FaChevronRight className="text-gray-700 text-sm" />
                </button>
                
                {/* Image Counter */}
                <div className="absolute top-3 right-3 bg-black/50 text-white text-xs px-2 py-1 rounded-full">
                  {currentImageIndex + 1} / {allImages.length}
                </div>
              </div>
            ) : (
              <div className="relative h-full">
                <img 
                  src={allImages[0]} 
                  alt={product.name} 
                  className="w-full h-full object-cover transition-transform duration-700 group-hover:scale-105 cursor-pointer"
                  loading="lazy"
                  onClick={handleImageClick}
                />
                <div className="absolute inset-0 bg-gradient-to-t from-black/5 to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-300"></div>
              </div>
            )}
            
            {/* Discount Badge */}
            {product.discount && (
              <div className="absolute top-3 left-3 bg-red-500 text-white px-2 py-1 rounded-full text-xs font-bold shadow-lg z-10">
                -{product.discount}%
              </div>
            )}
            
            {/* Quick View Button */}
            <button
              className="absolute bottom-3 right-3 bg-white/90 backdrop-blur-sm p-2 rounded-full shadow-md opacity-0 group-hover:opacity-100 transition-all duration-300 hover:bg-white hover:scale-110 z-10"
              onClick={() => onProductClick(product)}
            >
              <svg className="w-4 h-4 text-gray-700" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
              </svg>
            </button>
            
            {/* Zoom Button */}
            <button
              className="absolute bottom-3 left-3 bg-white/90 backdrop-blur-sm p-2 rounded-full shadow-md opacity-0 group-hover:opacity-100 transition-all duration-300 hover:bg-white hover:scale-110 z-10"
              onClick={handleImageClick}
            >
              <FaSearchPlus className="w-4 h-4 text-gray-700" />
            </button>
          </div>
          
          {/* Thumbnail Navigation */}
          {allImages.length > 1 && (
            <div className="px-4 pt-2 pb-4">
              <Swiper
                key={`${cardId}-thumbs`} // Unique key for thumbs swiper
                onSwiper={(swiper) => (thumbsSwiper.current = swiper)}
                spaceBetween={5}
                slidesPerView={4}
                freeMode={true}
                watchSlidesProgress={true}
                className="h-12"
              >
                {allImages.map((image, index) => (
                  <SwiperSlide key={`${cardId}-thumb-${index}`} className="opacity-60 hover:opacity-100 transition-opacity cursor-pointer rounded overflow-hidden">
                    <img 
                      src={image} 
                      alt={`${product.name} thumbnail ${index + 1}`} 
                      className="w-full h-full object-cover"
                    />
                  </SwiperSlide>
                ))}
              </Swiper>
            </div>
          )}
          
          {/* Content Section */}
          <div className="p-4">
            {/* Product Name */}
            <h3 className="text-lg font-semibold text-gray-800 mb-1 truncate">{product.name}</h3>
            
            {/* Rating */}
            <div className="flex items-center mb-2">
              <div className="flex text-yellow-400">
                {[...Array(5)].map((_, i) => (
                  <FaStar key={i} className={`text-xs ${i < (product.rating || 0) ? "text-yellow-400" : "text-gray-300"}`} />
                ))}
              </div>
              <span className="ml-1 text-xs text-gray-500">({product.reviews || 0})</span>
            </div>
            
            {/* Price */}
            <div className="flex items-baseline mb-3">
              <span className="text-lg font-bold text-gray-800">₵{product.price}</span>
              {product.original_price && (
                <span className="ml-2 text-sm text-gray-500 line-through">₵{product.original_price}</span>
              )}
            </div>
            
            {/* Add to Cart Button */}
            <button
              className="w-full py-2 px-3 bg-green-600 hover:bg-green-700 text-white font-medium rounded-md transition-all duration-300 flex items-center justify-center hover:shadow-lg transform hover:-translate-y-0.5"
              onClick={() => onProductClick(product)}
            >
              <FaShoppingCart className="mr-2 text-sm" />
              Add to Cart
            </button>
          </div>
        </div>
      </motion.div>
      
      {/* Image Zoom Modal */}
      <AnimatePresence>
        {isZoomed && (
          <motion.div
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/90 z-50 flex items-center justify-center p-4"
            onClick={closeZoom}
          >
            <motion.div
              initial={{ scale: 0.8, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.8, opacity: 0 }}
              transition={{ type: "spring", damping: 25, stiffness: 300 }}
              className="relative max-w-4xl max-h-full"
              onClick={(e) => e.stopPropagation()}
            >
              <button
                className="absolute -top-10 right-0 text-white hover:text-gray-300 transition-colors"
                onClick={closeZoom}
              >
                <FaTimes className="text-2xl" />
              </button>
              
              <Swiper
                key={`${cardId}-zoom`} // Unique key for zoom swiper
                modules={[Navigation, Pagination]}
                navigation
                pagination={{ clickable: true }}
                initialSlide={currentImageIndex}
                className="h-[70vh] w-full"
              >
                {allImages.map((image, index) => (
                  <SwiperSlide key={`${cardId}-zoom-${index}`} className="flex items-center justify-center">
                    <img 
                      src={image} 
                      alt={product.name} 
                      className="max-w-full max-h-full object-contain"
                    />
                  </SwiperSlide>
                ))}
              </Swiper>
              
              <div className="text-center text-white mt-4">
                <p className="text-lg font-medium">{product.name}</p>
                <p className="text-sm text-gray-300 mt-1">Image {currentImageIndex + 1} of {allImages.length}</p>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
};

export default ProductCard;