import React from 'react';
import {
  TouchableWithoutFeedbackProps,
  Pressable,
  Platform,
  TouchableOpacity,
} from 'react-native';
import { SENTRY_BREADCRUMB } from '../utils/debuggers/sentry-logger';

type IProps = TouchableWithoutFeedbackProps & {
  togglePress?: (isPressed: boolean) => void;
  pressDelayDuration?: number;
  touchableOpacityIos?: boolean;
  testID?: string;
  disabled?: boolean;
};

export const Touchable: React.FC<IProps> = props => {
  const isAndroid = Platform.OS === 'android';
  const {
    children,
    togglePress,
    pressDelayDuration,
    touchableOpacityIos,
    disabled,
    ...rest
  } = props;
  const TouchableIos =
    touchableOpacityIos && !disabled ? TouchableOpacity : Pressable;

  // special hack to make android support clicks normally
  if (isAndroid) {
    return (
      <Pressable
        {...rest}
        onPressIn={(e: any) => {
          if (disabled) {
            return;
          }

          if (togglePress) {
            togglePress(true);
          }
          if (rest.onPressIn) {
            rest.onPressIn(e);
          }
        }}
        onPress={() => {}}
        onPressOut={(e: any) => {
          if (disabled) {
            return;
          }

          if (rest.onPressOut) {
            rest.onPressOut(e);
          }
          if (rest.onPress) {
            rest.onPress(e);
          }
          if (togglePress) {
            togglePress(false);
          }

          SENTRY_BREADCRUMB.onPress(`<Touchable /> press: ${rest.testID}`);
        }}
        unstable_pressDelay={pressDelayDuration}
      >
        {children}
      </Pressable>
    );
  }

  return (
    <TouchableIos
      {...rest}
      onPress={e => {
        if (disabled) {
          return;
        }

        if (rest.onPress) {
          rest.onPress(e);
        }
      }}
      onPressIn={(e: any) => {
        if (disabled) {
          return;
        }

        if (togglePress) {
          togglePress(true);
        }
        if (rest.onPressIn) {
          rest.onPressIn(e);
        }
      }}
      onPressOut={(e: any) => {
        if (disabled) {
          return;
        }

        if (rest.onPressOut) {
          rest.onPressOut(e);
        }
        if (togglePress) {
          togglePress(false);
        }
      }}
    >
      {children}
    </TouchableIos>
  );
};

Touchable.defaultProps = {
  pressDelayDuration: 0,
};
