import React, { useEffect, useRef } from 'react';
import { Animated, Platform, StyleSheet } from 'react-native';
import type { IconProps } from '../Icon';
import { StyledFABIcon } from './StyledFAB';

const AnimatedIcons = Animated.createAnimatedComponent(
  React.forwardRef((props: IconProps, _) => <StyledFABIcon {...props} />)
);

type Props = {
  active?: boolean;
} & IconProps;

const AnimatedFABIcon = ({ active, ...iconProps }: Props) => {
  const rotateAnimation = useRef<Animated.Value>(
    new Animated.Value(active ? 1 : 0)
  );
  useEffect(() => {
    const animation = Animated.spring(rotateAnimation.current, {
      toValue: active ? 1 : 0,
      useNativeDriver: Platform.OS === 'ios' || Platform.OS === 'android',
    });

    animation.start();

    return () => {
      animation.stop();
    };
  }, [active]);

  const interpolatedRotateAnimation = rotateAnimation.current.interpolate({
    inputRange: [0, 1],
    outputRange: ['0deg', '-45deg'],
  });

  return (
    <Animated.View
      style={StyleSheet.flatten([
        {
          transform: [{ rotate: interpolatedRotateAnimation }],
        },
      ])}
    >
      <AnimatedIcons size="xsmall" {...iconProps} />
    </Animated.View>
  );
};

export { AnimatedFABIcon };
