import { useCallback, useEffect, useRef, useState } from "react";
import { Animated } from "react-native";

export const useAnimatedSelectedIndex = (
  startMilliseconds: number = 500,
  endMilliseconds: number = 500
) => {
  const selectedState = useRef(0);
  const [selectedStateIndex, setSelectedStateIndex] = useState(0);

  const backgroundImageAnimation = useRef(new Animated.Value(-300)).current;

  const onIndexChange = useCallback((index: number) => {
    if (index !== selectedState.current) {
      setTimeout(() => {}, 100);
      if (index == selectedState.current) return;
      selectedState.current = index;
      Animated.timing(backgroundImageAnimation, {
        toValue: -300,
        duration: endMilliseconds,
        useNativeDriver: true,
      }).start(() => {
        setSelectedStateIndex(index);
      });
    }
  }, []);

  useEffect(() => {
    Animated.timing(backgroundImageAnimation, {
      toValue: 0,
      duration: startMilliseconds,
      useNativeDriver: true,
    }).start();
  }, [selectedStateIndex]);

  return { onIndexChange, selectedStateIndex, backgroundImageAnimation };
};
