import React, { useEffect, useRef } from 'react';
import { Box } from '@nova-hf/ui';
import gsap from 'gsap';

import { parseMainColor } from '../../../beta/utils/typeGuards';
import PromotionalCard from '../../../frisco/PromotionalCard/PromotionalCard';
import { useOrderedListCollectionQuery } from '../../../typings/graphql';

type PromotionalSliderProps = {
  slug: string;
  limit: number;
};

const PromotionalSlider = ({ slug, limit }: PromotionalSliderProps) => {
  const { data } = useOrderedListCollectionQuery({
    variables: {
      where: {
        slug: slug,
      },
      limit: limit,
    },
  });

  const items = data?.orderedListCollection?.items[0]?.entriesCollection?.items || [];
  const sliderRef = useRef<HTMLDivElement | null>(null);
  const animationRef = useRef<gsap.core.Tween | null>(null);

  const duplicatedItems = [...items, ...items];

  useEffect(() => {
    if (!sliderRef.current || !items.length) return;

    const slider = sliderRef.current;
    const itemWidth = slider.scrollWidth / 2;

    if (animationRef.current) {
      animationRef.current.kill();
    }

    gsap.set(slider, { x: 0 });

    animationRef.current = gsap.to(slider, {
      x: `-=${itemWidth}px`,
      duration: 20,
      ease: 'linear',
      repeat: -1,
      onUpdate: function () {
        if (Math.abs(parseFloat(gsap.getProperty(slider, 'x') as string)) >= itemWidth) {
          gsap.set(slider, { x: 0 });
        }
      },
    });

    return () => {
      if (animationRef.current) {
        animationRef.current.kill();
      }
    };
  }, [items]);

  return (
    <Box style={{ overflow: 'hidden', position: 'relative' }}>
      <Box
        ref={sliderRef}
        style={{
          display: 'flex',
          flexDirection: 'row',
          gap: '16px',
          whiteSpace: 'nowrap',
          width: 'max-content',
        }}
      >
        {duplicatedItems.map(
          (item, index) =>
            item?.__typename === 'WwwCardComponent_cfContent' && (
              <Box key={`${item?._id}-${index}`} style={{ width: '300px', flex: '0 0 auto' }}>
                <PromotionalCard
                  image={item?.image?.url ?? ''}
                  title={item?.title ?? ''}
                  description={item?.description ?? ''}
                  color={parseMainColor(item?.color?.color ?? 'pink', 'pink')}
                />
              </Box>
            ),
        )}
      </Box>
    </Box>
  );
};

export default PromotionalSlider;
