import {useEffect} from 'react';
import {View} from 'react-native';
import {cancelAnimation, useSharedValue} from 'react-native-reanimated';
import Svg from 'react-native-svg';

import {SparklePath} from './components/SparklePath';
import {SPARKLES_ICON_VIEW_BOX, SPARKLES_STAR_PATHS} from './paths';
import {styles} from './styles';
import {buildSparkleCycle} from './utils';

interface Props {
  size: number;
  color: string;
  isAnimating: boolean;
}

export function AnimatedSparklesIcon({size, color, isAnimating}: Props) {
  const cycleProgress = useSharedValue(0);
  const isActive = useSharedValue(false);

  useEffect(() => {
    if (isAnimating) {
      isActive.value = true;
      cycleProgress.value = 0;
      cycleProgress.value = buildSparkleCycle();

      return () => {
        cancelAnimation(cycleProgress);
      };
    }

    cancelAnimation(cycleProgress);
    isActive.value = false;
    cycleProgress.value = 0;
  }, [cycleProgress, isActive, isAnimating]);

  return (
    <View style={[styles.container, {width: size, height: size}]}>
      <Svg width={size} height={size} viewBox={SPARKLES_ICON_VIEW_BOX}>
        {SPARKLES_STAR_PATHS.map((path, index) => (
          <SparklePath
            d={path.d}
            key={path.d}
            color={color}
            starIndex={index}
            isActive={isActive}
            fillRule={path.fillRule}
            cycleProgress={cycleProgress}
          />
        ))}
      </Svg>
    </View>
  );
}
