"use client";

import { useState, useRef, useEffect } from "react";
import { Swiper, SwiperSlide } from "swiper/react";
import { Pagination, Autoplay, Navigation } from "swiper/modules";
import "swiper/css";
import "swiper/css/pagination";
import { formattedPrice } from "@/utils";
import QuickAddPopup from "./QuickAddPopup"; // Adjust the import path as needed
import Link from "next/link";


const ProductRow = ({ title, products }: any) => {
  const [popupState, setPopupState] = useState<{
    show: boolean;
    product: any;
    position: { top: number; left: number };
  }>({
    show: false,
    product: null,
    position: { top: 0, left: 0 },
  });

  const buttonRefs = useRef<{ [key: string]: HTMLButtonElement | null }>({});
  const popupRef = useRef<HTMLDivElement | null>(null);

  const handleCartClick = (product: any, event: React.MouseEvent, index: number) => {
    const button = buttonRefs.current[`cart-btn-${index}`];
    if (!button) return;

    const rect = button.getBoundingClientRect();
    const popupWidth = 300;

    let left = rect.right - popupWidth;
    if (left < 10) {
      left = 10;
    }
    if (left + popupWidth > window.innerWidth - 10) {
      left = window.innerWidth - popupWidth - 10;
    }

    setPopupState({
      show: true,
      product: product,
      position: {
        top: rect.top - 10,
        left: left,
      },
    });
  };

  // Close popup when clicking outside
  useEffect(() => {
    const handleOutsideClick = (event: MouseEvent) => {
      const target = event.target as Node;

      // Check if click is outside both the cart button and the popup
      let isOutsidePopup = true;
      let isOutsideButton = true;

      // Check if click is on any cart button
      Object.values(buttonRefs.current).forEach((button) => {
        if (button && button.contains(target)) {
          isOutsideButton = false;
        }
      });

      // Check if click is on popup
      if (popupRef.current && popupRef.current.contains(target)) {
        isOutsidePopup = false;
      }

      if (isOutsideButton && isOutsidePopup) {
        setPopupState((prev) => ({ ...prev, show: false }));
      }
    };

    if (popupState.show) {
      document.addEventListener("mousedown", handleOutsideClick);
    }

    return () => {
      document.removeEventListener("mousedown", handleOutsideClick);
    };
  }, [popupState.show]);

  // Get product image (first image from variants or defaultImage)
  const getProductImage = (product: any) => {
    if (product.defaultImage) return product.defaultImage;
    if (product.variants?.[0]?.images?.[0]?.url) 
      return product.variants[0].images[0].url;
    if (product.images?.[0]) return product.images[0];
    return "/images/placeholder.jpg";
  };

  // Get product price
  const getProductPrice = (product: any) => {
    return product.price || product.minPrice || 0;
  };

  // Get original price
  const getOriginalPrice = (product: any) => {
    return product.maxPrice > product.price ? product.maxPrice : product.price;
  };

  return (
    <>
      <section className="productcontainer pt-2 py-10">
        <div className="container container-xxl px-3 mx-1">
          <div className="flex flex-wrap -mx-3">
            <div className="w-full px-3">
              <div className="section-heading md:text-center mb-8">
                <h2 className="text-3xl font-bold">{title}</h2>
              </div>
            </div>
          </div>
          <div className="flex flex-wrap -mx-3">
            <div className="relative px-3 w-full">
              <Swiper
                modules={[Navigation, Autoplay]}
                loop={true}
                autoplay={{
                  delay: 3000,
                  disableOnInteraction: true,
                }}
                navigation={{
                  nextEl: ".swiper-button-next-new-arrival",
                  prevEl: ".swiper-button-prev-new-arrival",
                }}
                spaceBetween={20}
                breakpoints={{
                  0: {
                    slidesPerView: 1,
                  },
                  576: {
                    slidesPerView: 2,
                  },
                  768: {
                    slidesPerView: 3,
                  },
                  1024: {
                    slidesPerView: 4,
                  },
                }}
              >
                {[...products, ...products].map((product, index) => (
                  <SwiperSlide key={index}>
                    <div className="productbx overflow-hidden border bg-white">
                      <div className="productbximg overflow-hidden relative">
                        {/* Discount Badge */}
                        {product.discount && product.discount > 0 && (
                          <div className="discountbx absolute top-2 left-2 z-10">
                            <span className="discounttxt bg-red-500 text-white px-2 py-1 rounded text-xs">
                              {product.discount}% Off
                            </span>
                          </div>
                        )}
                        <Link href={`/productdetails/${product.slug}`}>
                          <img
                            alt={product.name}
                            src={getProductImage(product)}
                            className="w-full max-h-350px object-cover hover:scale-105 transition duration-300"
                          />
                        </Link>
                      </div>

                      <div className="productcontent p-4">
                        <div className="flex gap-2 justify-between mb-2">
                          <h3 className="text-sm font-semibold px-2 line-clamp-2">
                            <Link href={`/productdetails/${product.slug}`}>
                              {product.name}
                            </Link>
                          </h3>

                          <div className="relative">
                            <button
                              ref={(el) => {
                                buttonRefs.current[`cart-btn-${index}`] = el;
                              }}
                              className="productcart mx-2"
                              type="button"
                              onClick={(e) => handleCartClick(product, e, index)}
                            >
                              <i className="icon icon-cart-bag"></i>

                              {/* Quick Add Popup */}
                              {popupState.show &&
                                popupState.product?._id === product._id && (
                                <QuickAddPopup
                                  popupRef={popupRef}
                                  product={{
                                    _id: popupState.product._id,
                                    name: popupState.product.name,
                                    image: getProductImage(popupState.product),
                                    price: getProductPrice(popupState.product),
                                    originalPrice: getOriginalPrice(popupState.product),
                                    skus: popupState.product.skus ?? [],
                                    variants: popupState.product.variants || [],
                                    totalQuantity: popupState.product.totalQuantity ?? 0,
                                  }}
                                  onClose={() => setPopupState((prev) => ({ ...prev, show: false }))}
                                  position={popupState.position}
                                />
                              )}
                            </button>
                          </div>
                        </div>

                        <div className="flex gap-2 justify-between">
                          <span className="crossprice line-through text-gray-400">
                            {formattedPrice(getOriginalPrice(product))}
                          </span>

                          <span className="price font-semibold">
                            {formattedPrice(getProductPrice(product))}
                          </span>
                        </div>
                      </div>
                    </div>
                  </SwiperSlide>
                ))}
              </Swiper>

              {/* Navigation */}
              <div className="swiper-nav mt-0">
                <div className="swiper-button-prev swiper-button-prev-new-arrival"></div>
                <div className="swiper-button-next swiper-button-next-new-arrival"></div>
              </div>
            </div>
          </div>
        </div>
      </section>

      
    </>
  );
};

export default ProductRow;