import React, { PropsWithChildren } from 'react';

import Animated, { Easing, useAnimatedStyle, useSharedValue, withSequence, withTiming } from 'react-native-reanimated';

interface IShakeAnimationProps extends PropsWithChildren {
  animate?: boolean;
  style?: object;
}

const useShakeAnimation = (show: boolean) => {
  const translateX = useSharedValue(0);

  React.useEffect(() => {
    if (show) {
      translateX.value = withSequence(
        withTiming(-1, { duration: 100, easing: Easing.bezier(0.36, 0.07, 0.19, 0.97) }),
        withTiming(2, { duration: 100, easing: Easing.bezier(0.36, 0.07, 0.19, 0.97) }),
        withTiming(-4, { duration: 100, easing: Easing.bezier(0.36, 0.07, 0.19, 0.97) }),
        withTiming(4, { duration: 100, easing: Easing.bezier(0.36, 0.07, 0.19, 0.97) }),
        withTiming(0, { duration: 100, easing: Easing.bezier(0.36, 0.07, 0.19, 0.97) }),
      );
    } else {
      translateX.value = withTiming(0, { duration: 200 });
    }
  }, [show, translateX]);

  return translateX;
};

const StyledAnimation: React.FC<IShakeAnimationProps> = ({ children, animate = false, style = {} }) => {
  const translateX = useShakeAnimation(animate);

  const animatedStyle = useAnimatedStyle(() => ({
    transform: [{ translateX: translateX.value }],
    backfaceVisibility: 'hidden',
    perspective: 1000,
  }));
  return <Animated.View style={[style, animatedStyle]}>{children}</Animated.View>;
};

export default StyledAnimation;
