import React, {memo, PropsWithChildren} from 'react';
import {PressableProps, ViewStyle} from 'react-native';
import Animated, {
  useAnimatedStyle,
  useSharedValue,
  withTiming,
} from 'react-native-reanimated';
import * as Haptics from 'expo-haptics';
import {ImpactFeedbackStyle} from 'expo-haptics';
import {Pressable} from '@components';
import {SPACING} from '@shared/theme';

const AnimatedPressable = Animated.createAnimatedComponent(Pressable);

interface PressableWrapperProps extends PressableProps {
  style?: ViewStyle | ViewStyle[];
  backgroundColor?: string;
  onPress?: () => void;
}

function PressableWrapper({
  children,
  style,
  backgroundColor,
  ...props
}: PropsWithChildren<PressableWrapperProps>) {
  const isPressedScaleValue = useSharedValue(1);

  const pressedAnimatedStyle = useAnimatedStyle(() => {
    if (!_WORKLET) {
      return {
        transform: [{scale: 1}],
      };
    }
    return {transform: [{scale: isPressedScaleValue.value}]};
  }, []);

  return (
    <AnimatedPressable
      {...props}
      backgroundColor={backgroundColor}
      hitSlop={SPACING.x4}
      onResponderStart={() => {
        Haptics.impactAsync(ImpactFeedbackStyle.Light);
        isPressedScaleValue.value = withTiming(0.8, {duration: 50});
      }}
      onResponderEnd={() => {
        isPressedScaleValue.value = withTiming(1, {duration: 50});
      }}
      useGestureHandler
      style={[style, pressedAnimatedStyle]}>
      {children}
    </AnimatedPressable>
  );
}

export default memo(PressableWrapper);
