/**
 * TimerRing — SVG circular progress indicator
 * Smooth animated arc that fills based on phase progress
 */

import React, { useRef, useEffect, useMemo } from 'react'
import { View, Animated, Easing, StyleSheet } from 'react-native'
import Svg, { Circle } from 'react-native-svg'

import { PHASE_COLORS, darkColors } from '@/src/shared/theme'
import { TIMER_RING_SIZE, TIMER_RING_STROKE } from '../constants'

type TimerPhase = 'PREP' | 'WORK' | 'REST' | 'COMPLETE'

const AnimatedCircle = Animated.createAnimatedComponent(Circle)

interface TimerRingProps {
  progress: number
  phase: TimerPhase
  size?: number
}

export function TimerRing({
  progress,
  phase,
  size = TIMER_RING_SIZE,
}: TimerRingProps) {
  const colors = darkColors
  const strokeWidth = TIMER_RING_STROKE
  const radius = (size - strokeWidth) / 2
  const circumference = 2 * Math.PI * radius
  const phaseColor = PHASE_COLORS[phase].fill

  const animatedProgress = useRef(new Animated.Value(0)).current
  const prevProgress = useRef(0)

  useEffect(() => {
    // If progress jumped backwards (new phase started), snap instantly
    if (progress < prevProgress.current - 0.05) {
      animatedProgress.setValue(progress)
    } else {
      Animated.timing(animatedProgress, {
        toValue: progress,
        duration: 1000,
        easing: Easing.linear,
        useNativeDriver: false,
      }).start()
    }
    prevProgress.current = progress
  }, [progress])

  const strokeDashoffset = animatedProgress.interpolate({
    inputRange: [0, 1],
    outputRange: [circumference, 0],
  })

  return (
    <View style={[styles.container, { width: size, height: size }]}>
      <Svg width={size} height={size}>
        {/* Background track */}
        <Circle
          cx={size / 2}
          cy={size / 2}
          r={radius}
          stroke={colors.border.dim}
          strokeWidth={strokeWidth}
          fill="none"
        />
        {/* Progress arc */}
        <AnimatedCircle
          cx={size / 2}
          cy={size / 2}
          r={radius}
          stroke={phaseColor}
          strokeWidth={strokeWidth}
          fill="none"
          strokeLinecap="round"
          strokeDasharray={circumference}
          strokeDashoffset={strokeDashoffset}
          rotation="-90"
          origin={`${size / 2}, ${size / 2}`}
        />
      </Svg>
      {/* Phase glow effect */}
      <View
        style={[
          styles.glow,
          {
            width: size + 24,
            height: size + 24,
            borderRadius: (size + 24) / 2,
            backgroundColor: phaseColor,
          },
        ]}
      />
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    alignItems: 'center',
    justifyContent: 'center',
  },
  glow: {
    position: 'absolute',
    opacity: 0.06,
    zIndex: -1,
  },
})
