import React, { useLayoutEffect, useRef } from 'react';
import { Animated, Easing, Platform, StyleSheet } from 'react-native';

import { StyledSpinnerDot, StyledSpinnerRow } from './StyledSpinner';

const AnimatedRow = Animated.createAnimatedComponent(StyledSpinnerRow);

const AnimatedDot = Animated.createAnimatedComponent(StyledSpinnerDot);

const AnimatedSpinner = ({
  size,
  intent,
}: {
  size: 'small' | 'medium';
  intent: 'primary' | 'inverted';
}) => {
  const rotateAnimation = useRef<Animated.Value>(new Animated.Value(0));

  useLayoutEffect(() => {
    const animation = Animated.loop(
      Animated.timing(rotateAnimation.current, {
        toValue: 1,
        duration: 1200,
        easing: Easing.linear,
        useNativeDriver: Platform.OS !== 'web',
      })
    );

    animation.start();

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

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

  const rowProps = {
    themeSize: size,
  };

  const dotProps = {
    themeSize: size,
    themeIntent: intent,
  };

  return (
    <Animated.View
      style={StyleSheet.flatten([
        {
          transform: [{ rotate: interpolatedRotateAnimation }],
        },
      ])}
    >
      <AnimatedRow themePosition="top" {...rowProps}>
        <AnimatedDot themePosition="topLeft" {...dotProps} />
        <AnimatedDot themePosition="topRight" {...dotProps} />
      </AnimatedRow>
      <AnimatedRow themePosition="bottom" {...rowProps}>
        <AnimatedDot themePosition="bottomLeft" {...dotProps} />
        <AnimatedDot themePosition="bottomRight" {...dotProps} />
      </AnimatedRow>
    </Animated.View>
  );
};

export { AnimatedSpinner };
