import * as React from 'react';
import { FC, useRef, useState, useEffect } from 'react';
import { style } from 'typestyle';
import { IMedia, IProduct } from '../../../../../../types';
import ProductListItem from './ProductListItem';

interface ProductContainerProps {
  products: IProduct[];
  startIndex: number;
  onRefUpdate: (index: number, ref: HTMLDivElement | null) => void;
  parentMedia: IMedia;
  onAddToCart?: (product: IProduct, media: IMedia) => void;
}

const ProductListContainer: FC<ProductContainerProps> = ({
  products,
  startIndex,
  onRefUpdate,
  parentMedia,
  onAddToCart,
}) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const [containerWidth, setContainerWidth] = useState<number>(0);

  useEffect(() => {
    if (containerRef.current) {
      setContainerWidth(containerRef.current.clientWidth);
    }
  }, []);

  return (
    <div ref={containerRef} className={styles.productContainer}>
      {products.map((product, i) => (
        <div
          key={product.id}
          className={styles.productLine}
          ref={(ref) => {
            onRefUpdate(startIndex + i, ref);
          }}
        >
          <ProductListItem
            isVisible={true}
            product={product}
            parentMedia={parentMedia}
            containerWidth={containerWidth}
            onAddToCart={onAddToCart}
          />
        </div>
      ))}
    </div>
  );
};

const styles = {
  productContainer: style({
    display: 'flex',
    flexDirection: 'column',
    gap: '10px',
    width: '100%',
    margin: '10px 0',
  }),

  productLine: style({
    width: '100%',
    height: '100%',
    minHeight: '80px',
    display: 'flex',
    flexDirection: 'column',
    justifyContent: 'center',
  }),
};

export default ProductListContainer;
