import { Gesture, GestureDetector } from 'react-native-gesture-handler'
import Animated, {
  runOnJS,
  type SharedValue,
  useAnimatedStyle,
} from 'react-native-reanimated'
import { View } from 'tamagui'

type Props = {
  onTap: () => void
  onLongPressStart: () => void
  onLongPressEnd: () => void
  isRecording: boolean
  progress: SharedValue<number>
}

export function ShutterButton({
  onTap,
  onLongPressStart,
  onLongPressEnd,
  isRecording,
  progress,
}: Props) {
  const tap = Gesture.Tap()
    .maxDuration(250)
    .onEnd((_, success) => {
      if (success) runOnJS(onTap)()
    })
  const long = Gesture.LongPress()
    .minDuration(180)
    .onStart(() => runOnJS(onLongPressStart)())
    .onEnd(() => runOnJS(onLongPressEnd)())
    .onFinalize(() => runOnJS(onLongPressEnd)())
  const composed = Gesture.Race(long, tap)

  const ringStyle = useAnimatedStyle(() => ({
    transform: [{ scale: 1 + progress.value * 0.08 }],
    opacity: 0.35 + progress.value * 0.65,
  }))

  return (
    <GestureDetector gesture={composed}>
      <View width={88} height={88} alignItems="center" justifyContent="center">
        <Animated.View
          style={[
            {
              position: 'absolute',
              width: 88,
              height: 88,
              borderRadius: 44,
              borderWidth: 3,
              borderColor: isRecording ? '#FF3B30' : 'rgba(255,255,255,0.6)',
            },
            ringStyle,
          ]}
        />
        <View
          width={68}
          height={68}
          borderRadius={34}
          backgroundColor={isRecording ? '#FF3B30' : 'white'}
        />
      </View>
    </GestureDetector>
  )
}
