import React, { FC } from 'react';
import {
  Platform,
  TextInput,
  TextInputProps,
  TouchableOpacity,
} from 'react-native';
import { Styles } from '../Consts';

interface SystemTextInputProps extends TextInputProps {
  ref?: React.RefObject<TextInput | null>;
}

const SystemTextInput: FC<SystemTextInputProps> = props => {
  const { editable, onPressIn, onPressOut, ref } = props;

  const needsAndroidWrapper =
    Platform.OS === 'android' && !editable && (onPressIn || onPressOut);

  const inputProps: TextInputProps = {
    ...props,
    ...(needsAndroidWrapper
      ? { onPressIn: undefined, onPressOut: undefined }
      : null),
    ...(editable === false ? { accessibilityState: undefined } : null),
  };

  if (needsAndroidWrapper) {
    return (
      <TouchableOpacity
        activeOpacity={1}
        onPressIn={onPressIn}
        onPressOut={onPressOut}
        style={Styles.flex}
      >
        <TextInput ref={ref} {...inputProps} pointerEvents="none" />
      </TouchableOpacity>
    );
  }

  return <TextInput ref={ref} {...inputProps} />;
};

export default SystemTextInput;
