import React, { useRef, useEffect } from 'react';
import { Animated, Easing } from 'react-native';
import Svg, { Circle } from 'react-native-svg';
import { CircularProgressBaseProps } from '@digigov/react-core/CircularProgressBase';

export const CircularProgress: React.FC<CircularProgressBaseProps> = ({
  size = 'md',
  color = 'primary',
}) => {
  const sizes = {
    sm: 20,
    md: 40,
    lg: 50,
  };
  const strokeWidth = sizes[size] / 4;
  const radius = (sizes[size] - strokeWidth) / 2;
  const circumference = 2 * Math.PI * radius;
  const rotateAnim = useRef(new Animated.Value(0)).current;
  const dashAnim = useRef(new Animated.Value(circumference)).current;

  const progressColor = color === 'primary' ? '#003375' : '#fff';
  const backgroundColor = '#01b0f0';
  const duration = 4000;

  useEffect(() => {
    Animated.loop(
      Animated.timing(rotateAnim, {
        toValue: 1,
        duration: 10000,
        easing: Easing.linear,
        useNativeDriver: true,
      })
    ).start();
  }, [rotateAnim]);

  useEffect(() => {
    Animated.loop(
      Animated.sequence([
        Animated.timing(dashAnim, {
          toValue: 0,
          duration: duration * 0.4,
          easing: Easing.inOut(Easing.ease),
          useNativeDriver: true,
        }),
        Animated.timing(dashAnim, {
          toValue: circumference,
          duration: duration * 0.6,
          easing: Easing.inOut(Easing.ease),
          useNativeDriver: true,
        }),
      ])
    ).start();
  }, [dashAnim, duration, circumference]);

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

  return (
    <Animated.View
      style={[
        {
          width: sizes[size],
          height: sizes[size],
          transform: [{ rotate: rotateInterpolate }],
        },
      ]}
    >
      <Svg
        width={sizes[size]}
        height={sizes[size]}
        viewBox={`0 0 ${sizes[size]} ${sizes[size]}`}
      >
        <Circle
          cx={sizes[size] / 2}
          cy={sizes[size] / 2}
          r={radius}
          stroke={backgroundColor}
          strokeWidth={strokeWidth}
          fill="none"
        />
        <AnimatedCircle
          cx={sizes[size] / 2}
          cy={sizes[size] / 2}
          r={radius}
          stroke={progressColor}
          strokeWidth={strokeWidth}
          strokeDasharray={`${circumference}`}
          strokeDashoffset={dashAnim}
          fill="none"
        />
      </Svg>
    </Animated.View>
  );
};

const AnimatedCircle = Animated.createAnimatedComponent(Circle);
