import { useEffect, useState, useRef, RefObject, createRef } from 'react';

interface IProps {
  setProgressbarIndex: (index: number) => void;
  count: number;
}

const useProgress = ({
  setProgressbarIndex,
  count
}: IProps) => {
  const [progressbarRefs, setProgressbarRefs] = useState<RefObject<HTMLDivElement>[]>([]);
  const index = useRef<number>(0);
  const setIndex = (i: number) => {
    index.current = i;
  };
  const unmounted = useRef<boolean>(false);

  useEffect(() => {
    setProgressbarRefs((elRefs) =>
      [...new Array(count).keys()].map((_, i) => elRefs[i] || createRef()),
    );
  }, []);

  useEffect(() => {
    let id: NodeJS.Timeout | null = null;
    if (progressbarRefs.length === count) {
      id = moveBar(unmounted).intervalId;
    }

    return () => {
      if (id) {
        unmounted.current = true;
        clearInterval(id);
      }
    };
  }, [progressbarRefs.length]);


  const clearProgressStyle = () => {
    progressbarRefs.forEach(item => {
      if (item.current) {
        item.current.style.width = '0';
      }
    });
  };

  const moveBar = (unmounted: React.MutableRefObject<boolean>) => {
    const elem = progressbarRefs[index.current].current;
    let width = 1;
    const id = setInterval(frame, 50);

    function frame() {
      if (unmounted.current) {
        return;
      }

      if (width >= 100) {
        clearInterval(id);
        const i = index.current + 1;

        if (i < count) {
          setIndex(i);
          setProgressbarIndex(i);
          moveBar(unmounted);
        } else {
          clearProgressStyle();
          setIndex(0);
          setProgressbarIndex(0);
          moveBar(unmounted);
        }
      } else {
        width += 1;
        if (elem) {
          elem.style.width = width + '%';
        }
      }
    }

    return { intervalId: id };
  };

  return {
    progressbarRefs,
  };
};

export default useProgress;
