import debounce from "lodash/debounce";
import { Factory } from "native-base";
import React from "react";
import {
  GestureResponderEvent,
  TouchableOpacity,
  TouchableOpacityProps,
} from "react-native";

const StyledEnhancedTouchableOpacity: React.FC<
  TouchableOpacityProps & {
    as?: React.ComponentType<any>;
    debounceDuration?: number;
  }
> = ({ as = TouchableOpacity, debounceDuration, onPress, ...rest }) => {
  const onPressDebounce = debounce(
    (event: GestureResponderEvent) => onPress?.(event),
    debounceDuration ?? 500,
    {
      leading: true,
      trailing: false,
    }
  );

  const TheComponent = as;

  return <TheComponent onPress={onPressDebounce} {...rest} />;
};

export const EnhancedTouchableOpacity = Factory(StyledEnhancedTouchableOpacity);

export default React.memo(EnhancedTouchableOpacity);
