import * as React from 'react';
import { FC, useRef, useState, useEffect } from 'react';
import { style } from 'typestyle';
import { IMedia, IProduct } from '../../../../../../types';
import ProductModalItem from '../ProductModalContainer/ProductModalItem';
import Arrow from '../../../../../Icons/Arrows/Arrow';
import { productCarouselGap } from '../../../../../consts';
import { useProductCarousel } from '../../../../../../hooks/useProductCarousel';

interface ProductCarouselProps {
  products: IProduct[];
  parentMedia: IMedia; 
  isSingleSection?: boolean;
  onAddToCart?: (product: IProduct, media: IMedia) => void;
}

const ProductCarousel: FC<ProductCarouselProps> = ({
  products,
  parentMedia,
  isSingleSection,
  onAddToCart,
}) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const scrollContainerRef = useRef<HTMLDivElement>(null);
  const [containerHeight, setContainerHeight] = useState<number>(0);

  // Use the  carousel hook
  const {
    canScrollPrev,
    canScrollNext,
    enableTransition,
    scrollPrev,
    scrollNext,
    getScrollPosition,
    getItemWidth,
  } = useProductCarousel({
    products,
    containerRef,
    scrollContainerRef,
  });

  // Handle container height calculation
  useEffect(() => {
    if (!containerRef.current) return;

    const resizeObserver = new ResizeObserver((entries) => {
      const { height } = entries[0].contentRect;
      setContainerHeight(height);
    });

    resizeObserver.observe(containerRef.current);
    return () => resizeObserver.disconnect();
  }, []);

  return (
    <div className={styles.carouselWrapper(isSingleSection)} ref={containerRef}>
      <Arrow
        direction='left'
        disabled={!canScrollPrev}
        onClick={() => scrollPrev()}
        show={canScrollPrev || canScrollNext}
        classPrefix='product-carousel'
        ariaLabel='Previous products'
      />

      <div className={styles.scrollContainer} ref={scrollContainerRef}>
        <div 
          className={styles.slideContainer}
          style={{
            transform: `translateX(-${getScrollPosition()}px)`,
            transition: enableTransition 
              ? 'transform 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94)' 
              : 'none',
          }}
        >
          {products.map((product, index) => (
            <div 
              key={product.id} 
              className={styles.slide}
              style={{ 
                width: getItemWidth(index),
                marginRight: index < products.length - 1 ? `${productCarouselGap}px` : '0'
              }}
            >
              <ProductModalItem
                isVisible={true}
                product={product}
                parentMedia={parentMedia}
                containerHeight={containerHeight}
                isSingleSection={isSingleSection}
                onAddToCart={onAddToCart}
              />
            </div>
          ))}
        </div>
      </div>

      <Arrow
        direction='right'
        disabled={!canScrollNext}
        onClick={() => scrollNext()}
        show={canScrollPrev || canScrollNext}
        classPrefix='product-carousel'
        ariaLabel='Next products'
      />
    </div>
  );
};

const styles = {
  carouselWrapper: (_isSingleSection?: boolean) => style({
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    width: '100%',
    flex: 1,
    minHeight: 0,
    gap: '10px',
    position: 'relative',
  }),

  scrollContainer: style({
    overflow: 'hidden',
    flex: 1,
    height: '100%',
    position: 'relative',
  }),

  carouselButton: style({
    backgroundColor: 'transparent',
    border: 'none',
    padding: 0,
    display: 'flex',
    alignItems: 'center',
    cursor: 'pointer',
  }),

  slideContainer: style({
    display: 'flex',
    alignItems: 'center',
    height: '100%',
    willChange: 'transform',
  }),

  slide: style({
    position: 'relative',
    flex: '0 0 auto',
    height: '100%',
  }),
};

export default ProductCarousel;
