import * as React from 'react';
import {default as SlickSlider} from 'react-slick';

interface Props extends React.ComponentProps<typeof SlickSlider> {
  ref?: React.MutableRefObject<SlickSlider | null>;
}

const Slider = (props: Props) => {
  const {initialSlide} = props;
  const fallbackSliderRef = React.useRef<SlickSlider | null>(null);
  const sliderRef = props.ref || fallbackSliderRef;

  const hasSetPosition = React.useRef<boolean>(false);

  /**
   * workaround for issue changing slide works incorrect when infinite is false and initialSlide > 1
   * https://github.com/akiran/react-slick/issues/1946#issuecomment-768935762
   */
  React.useEffect(() => {
    if (
      sliderRef.current &&
      !hasSetPosition.current &&
      typeof initialSlide === 'number'
    ) {
      sliderRef.current.slickGoTo(initialSlide);
      hasSetPosition.current = true;
    }
    // run on first render only
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return <SlickSlider {...props} ref={sliderRef} />;
};

export default React.memo(Slider);
