import React, {ReactNode} from 'react';
import {
  Pressable as RNPressable,
  PressableProps,
  StyleProp,
  ViewStyle,
} from 'react-native';
import Animated, {
  interpolate,
  useAnimatedStyle,
  useSharedValue,
  withTiming,
} from 'react-native-reanimated';
import * as Haptics from 'expo-haptics';

interface Props extends PressableProps {
  children: ReactNode;
  onPress?: () => void;
  style?: StyleProp<ViewStyle>;
}

export function PressableReaction({children, onPress, style, ...props}: Props) {
  const pressed = useSharedValue(0);

  const handlePressIn = () => {
    Haptics.selectionAsync();
    pressed.value = withTiming(1, {duration: 200});
  };

  const handlePressOut = () => {
    Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Rigid);
    pressed.value = withTiming(0, {duration: 200});
  };

  const handlePress = () => onPress?.();

  const animatedStyle = useAnimatedStyle(() => {
    if (!_WORKLET) {
      return {
        transformOrigin: 'bottom',
        transform: [{scale: 1}, {translateY: 0}],
      };
    }

    return {
      transformOrigin: 'bottom',
      transform: [
        {
          scale: interpolate(pressed.value, [0, 1], [1, 1.75]),
        },
        {
          translateY: interpolate(pressed.value, [0, 1], [0, -5]),
        },
      ],
    };
  });

  return (
    <RNPressable
      onPressIn={handlePressIn}
      onPressOut={handlePressOut}
      onPress={handlePress}
      {...props}>
      <Animated.View style={[style, animatedStyle]}>{children}</Animated.View>
    </RNPressable>
  );
}
