import { placeHolderImage } from "@/components/widgets/Placeholder";
import Image from "next/image";
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { RiHeadphoneLine, RiVideoLine } from "react-icons/ri";
import ImageZoom from "react-image-zooom";
import Slider from "react-slick";
import { Col, Row } from "reactstrap";
import DigitalImageOptions from "../common/DigitalImageOptions";
import SlickArrowLeft from "../common/SlickArrowLeft";
import SlickArrowRight from "../common/SlickArrowRight";

// Helper to get proper image URL
const getProperImageUrl = (url) => {
  if (!url) return placeHolderImage;

  // If it's already a full URL, return as-is
  if (typeof url === 'string' && (url.startsWith('http://') || url.startsWith('https://'))) {
    return url;
  }

  // If it's a local asset path
  if (typeof url === 'string' && url.startsWith('/assets/')) {
    return url;
  }

  // Check if it looks like a valid file path (has extension or path separator)
  if (typeof url === 'string' && url.length > 0) {
    const hasExtension = /\.(jpg|jpeg|png|gif|webp|svg|bmp|avif)$/i.test(url);
    const hasPathIndicator = url.includes('/') || url.includes('\\') || url.startsWith('storage');

    // If it doesn't look like a file path, return placeholder
    if (!hasExtension && !hasPathIndicator) {
      return placeHolderImage;
    }

    const backendUrl = process.env.NEXT_PUBLIC_BACKEND_IMAGE_URL || process.env.BACKEND_IMAGE_URL || '';
    return `${backendUrl}${url.startsWith('/') ? '' : '/'}${url}`;
  }

  return placeHolderImage;
};

const ThumbnailProductImage = ({ productState, slideToShow }) => {
  const { t } = useTranslation("common");
  const [state, setState] = useState({ nav1: null, nav2: null });
  const [videoType, setVideoType] = useState([
    "video/mp4",
    "video/webm",
    "video/ogg",
  ]);
  const [audioType, setAudioType] = useState([
    "audio/mpeg",
    "audio/wav",
    "audio/ogg",
  ]);
  const slider1 = useRef();
  const slider2 = useRef();
  const { nav1, nav2 } = state;
  // Helper to find selected color from variation
  const getSelectedColor = () => {
    if (!productState?.selectedVariation?.attribute_values) return null;
    const colorAttr = productState.selectedVariation.attribute_values.find((av) => {
      const attrName = av.attribute?.name?.toLowerCase() || '';
      const attrSlug = av.attribute?.slug?.toLowerCase() || '';
      return attrName === 'color' || attrSlug === 'color';
    });
    return colorAttr?.value || null;
  };

  // Helper to filter images by color name
  const filterImagesByColor = (images, colorName) => {
    if (!images || !colorName) return images;
    const colorUpper = colorName.toUpperCase();
    const filtered = images.filter((img) => {
      const imageUrl = (img.original_url || img.image || img.image_url || '').toUpperCase();
      return imageUrl.includes(`-${colorUpper}-`) ||
             imageUrl.includes(`_${colorUpper}_`) ||
             imageUrl.includes(`/${colorUpper}.`) ||
             imageUrl.includes(`-${colorUpper}.`);
    });
    // Return filtered if found, otherwise return all images
    return filtered.length > 0 ? filtered : images;
  };

  // Support both variation galleries and main product galleries
  const getImageGalleries = () => {
    const backendUrl = process.env.NEXT_PUBLIC_BACKEND_IMAGE_URL || process.env.BACKEND_IMAGE_URL || "";
    const selectedColor = getSelectedColor();

    // Priority 1: Selected variation galleries (already filtered by color in transformation)
    if (productState?.selectedVariation?.variation_galleries?.length > 0) {
      return productState.selectedVariation.variation_galleries;
    }

    // Priority 2: Product galleries - filter by selected color
    if (productState?.product?.product_galleries?.length > 0) {
      return filterImagesByColor(productState.product.product_galleries, selectedColor);
    }

    // Priority 3: Product images array - filter by selected color
    if (productState?.product?.images?.length > 0) {
      const mappedImages = productState.product.images.map((img) => ({
        id: img.id,
        original_url: img.image_url || img.image || img.original_url,
        name: img.alt_text || `Product Image ${img.id}`,
        mime_type: "image/jpeg",
      }));
      return filterImagesByColor(mappedImages, selectedColor);
    }

    // Priority 4: Product media array (from new API structure)
    if (productState?.product?.media?.length > 0) {
      const mappedMedia = productState.product.media.map((media) => ({
        id: media.id,
        original_url: media.url.startsWith('http') ? media.url : `${backendUrl}${media.url}`,
        name: `Product Image ${media.id}`,
        mime_type: "image/jpeg",
      }));
      return filterImagesByColor(mappedMedia, selectedColor);
    }

    // Priority 5: Product thumbnail as array
    if (productState?.product?.product_thumbnail?.original_url) {
      return [productState.product.product_thumbnail];
    }

    // Priority 6: Main image from product
    if (productState?.product?.main_image) {
      return [{
        id: 'main',
        original_url: productState.product.main_image.startsWith('http')
          ? productState.product.main_image
          : `${backendUrl}${productState.product.main_image}`,
        name: 'Main Product Image',
        mime_type: "image/jpeg",
      }];
    }

    // Priority 7: Selected variation image as array
    if (productState?.selectedVariation?.variation_image?.original_url) {
      return [productState.selectedVariation.variation_image];
    }

    return [];
  };

  const selectedColor = getSelectedColor();
  const currentVariation = getImageGalleries();

  // Create a unique key for slider based on color and variation
  const sliderKey = `${selectedColor || 'default'}-${productState?.selectedVariation?.id || 'none'}`;

  // Initialize and update slider references
  useEffect(() => {
    // Reset state first to clear stale references
    setState({ nav1: null, nav2: null });

    // Delay state update to ensure sliders are mounted
    const timer = setTimeout(() => {
      if (slider1.current && slider2.current) {
        setState({
          nav1: slider1.current,
          nav2: slider2.current,
        });
      }
    }, 150);

    return () => clearTimeout(timer);
  }, [currentVariation.length, productState?.selectedVariation?.id, selectedColor]);

  // Update slider when selected variation or color changes
  useEffect(() => {
    // Add a small delay to ensure sliders are mounted
    const timer = setTimeout(() => {
      if (
        slider1.current &&
        slider1.current.slickGoTo &&
        productState?.selectedVariation
      ) {
        try {
          // Always reset to first slide when color changes
          slider1.current.slickGoTo(0);
        } catch (error) {
          console.warn("Slider navigation error:", error);
        }
      }
    }, 200);

    return () => clearTimeout(timer);
  }, [
    productState?.selectedVariation?.id,
    selectedColor,
  ]);

  let mainSliderSettings = {
    adaptiveHeight: true,
    arrows: currentVariation.length > 1,
    infinite: false,
    slidesToShow: 1,
    slidesToScroll: 1,
  };

  let thumbnailSlider = {
    loop: false,
    focusOnSelect: true,
    arrows: false,
    swipeToSlide: true,
    responsive: [
      {
        breakpoint: 1200,
        settings: {
          slidesToShow: 3,
        },
      },
      {
        breakpoint: 992,
        settings: {
          slidesToShow: 4,
        },
      },
      {
        breakpoint: 576,
        settings: {
          slidesToShow: 3,
        },
      },
      {
        breakpoint: 450,
        settings: {
          slidesToShow: 2,
        },
      },
    ],
  };

  return (
    <div className="sticky-top-custom">
      <div className="thumbnail-image-slider">
        <Row className="g-sm-4 g-3">
          <Col xs={12}>
            <div
              className={`product-slick position-relative main-product-box ${
                currentVariation.length <= 1 ? "no-arrow" : ""
              }`}
            >
              {productState?.product?.is_sale_enable ||
              productState?.product?.is_trending ||
              productState?.product?.is_featured ? (
                <ul className="product-detail-label">
                  {productState?.product.is_sale_enable ? (
                    <li className="soldout">{t("Sale")}</li>
                  ) : (
                    ""
                  )}
                  {productState?.product.is_trending ? (
                    <li className="trending">{t("Trending")}</li>
                  ) : (
                    ""
                  )}
                  {productState?.product.is_featured ? (
                    <li className="featured">{t("Featured")}</li>
                  ) : (
                    ""
                  )}
                </ul>
              ) : null}

              {currentVariation.length > 0 ? (
                <Slider
                  key={`main-slider-${sliderKey}`}
                  {...mainSliderSettings}
                  asNavFor={currentVariation.length > 1 && nav2 ? nav2 : undefined}
                  ref={slider1}
                  prevArrow={<SlickArrowLeft />}
                  nextArrow={<SlickArrowRight />}
                >
                  {currentVariation.map((image, i) => (
                    <div key={i}>
                      <div className="slider-image">
                        {videoType.includes(image?.mime_type) ? (
                          <>
                            <video className="w-100 " controls>
                              <source
                                src={image ? image?.original_url : ""}
                                type={image?.mime_type}
                              ></source>
                            </video>
                          </>
                        ) : audioType.includes(image?.mime_type) ? (
                          <div className="slider-main-img">
                            <audio controls>
                              <source
                                src={image ? image.original_url : ""}
                                type={image.mime_type}
                              ></source>
                            </audio>
                          </div>
                        ) : (
                          <ImageZoom
                            src={getProperImageUrl(image?.original_url)}
                            alt={image?.name || "Product image"}
                            zoom="200"
                            className="img-fluid"
                            height={670}
                            width={670}
                          />
                        )}
                      </div>
                    </div>
                  ))}
                </Slider>
              ) : (
                <img
                  src={getProperImageUrl(productState?.product?.product_thumbnail?.original_url)}
                  className="img-fluid"
                  alt={productState?.product?.name || "Product"}
                />
              )}

              {productState?.product?.product_type == "digital" && (
                <DigitalImageOptions product={productState?.product} />
              )}
            </div>
          </Col>
          <Col xs={12}>
            {currentVariation.length > 1 && (
              <Slider
                key={`thumb-slider-${sliderKey}`}
                {...thumbnailSlider}
                className="slider-nav thumbnail-slider-box"
                asNavFor={nav1 || undefined}
                ref={slider2}
                slidesToShow={Math.min(
                  currentVariation.length,
                  slideToShow || 4
                )}
                slidesToScroll={1}
                infinite={false}
              >
                {currentVariation?.map((image, i) => (
                  <div key={i} className="slider-image">
                    {videoType.includes(image.mime_type) ? (
                      <>
                        <div className="video-icon">
                          <RiVideoLine />
                        </div>
                        <video width="130" height="130">
                          <source
                            src={image ? image?.original_url : ""}
                            type={image?.mime_type}
                          />
                        </video>
                      </>
                    ) : audioType.includes(image?.mime_type) ? (
                      <span>
                        <RiHeadphoneLine size={100} />
                      </span>
                    ) : (
                      <Image
                        src={getProperImageUrl(image?.original_url)}
                        alt={image?.name || "Product image"}
                        className="img-fluid"
                        height={130}
                        width={130}
                      />
                    )}
                  </div>
                ))}
              </Slider>
            )}
          </Col>
        </Row>
      </div>
    </div>
  );
};

export default ThumbnailProductImage;
