import { useEffect, useRef, useState } from 'react';
const useAnimateDataChange = ({
  trigger
}) => {
  const animationRef = useRef();
  const [displayValue, setDisplayValue] = useState(trigger);

  // Animate out when the trigger changes, then set a new value to display
  useEffect(() => {
    if (!animationRef.current) return;
    const timing = [{
      opacity: 1,
      transform: 'rotateX(0deg)'
    }, {
      opacity: 0,
      transform: 'rotateX(90deg)'
    }];
    const fadeOut = animationRef.current.animate(timing, {
      duration: 150,
      fill: 'forwards'
    });
    fadeOut.onfinish = () => {
      fadeOut.commitStyles();
      setDisplayValue(trigger);
      fadeOut.cancel();
    };
  }, [trigger]);

  // Animate in when we change the display value
  useEffect(() => {
    if (!animationRef.current) return;
    const timing = [{
      opacity: 0,
      transform: 'rotateX(90deg)'
    }, {
      opacity: 1,
      transform: 'rotateX(0deg)'
    }];
    const fadeIn = animationRef.current.animate(timing, {
      duration: 250,
      fill: 'forwards'
    });
    fadeIn.onfinish = () => {
      fadeIn.commitStyles();
      fadeIn.cancel();
    };
  }, [displayValue]);
  return [animationRef, displayValue];
};
export default useAnimateDataChange;