import { useCallback, useEffect, useMemo, useState } from "react";

const useSkeleton = (skeletonOptions) => {
  const [transitionStage, setTransitionStage] = useState(1);

  // After how long skeleton changes screen
  const timeoutInterval = useMemo(() => {
    return skeletonOptions?.timeoutInterval || 900;
  });

  // isLoadingIndicator is boolean that indicates should skeleton screen be shown
  const isLoadingIndicator = useMemo(() => {
    return skeletonOptions?.isLoadingIndicator;
  }, [skeletonOptions]);

  // Timeout function to change transition stage
  const timeout = useCallback(() => {
    setTransitionStage((prevTransitionStage) => {
      if (prevTransitionStage === 2) return 1;
      return prevTransitionStage + 1;
    });
  }, [transitionStage]);

  useEffect(() => {
    let newTimeout;
    if (isLoadingIndicator) {
      newTimeout = setTimeout(timeout, timeoutInterval);
    }
    return () => clearTimeout(newTimeout);
  }, [timeout, isLoadingIndicator]);

  return {
    transitionStage,
  };
};
export default useSkeleton;
