import React, {forwardRef, useMemo} from 'react';
import {
  NativeSyntheticEvent,
  TextInput as RNTextInput,
  TextInputProps as RNTextInputProps,
} from 'react-native';
import {useTranslation} from 'react-i18next';
import {BottomSheetTextInput} from '@gorhom/bottom-sheet';
import {useTheme} from '@shared/theme';

import {styles} from './styles';

export interface TextInputProps extends RNTextInputProps {
  useBottomSheetTextInput?: boolean;
  focused?: boolean;
  textAlignVertical?: 'auto' | 'top' | 'bottom' | 'center';
  size?: 'lg' | 'sm';
  /**
   * Event is defined only for iOS, on Android it is `undefined` and called onPasteImage()
   **/
  onPasteImage?: (
    e: NativeSyntheticEvent<{uri: string; bytes: number}>,
  ) => void;
}

export const TextInput = forwardRef<RNTextInput, TextInputProps>(
  (
    {
      useBottomSheetTextInput,
      multiline,
      style,
      textAlignVertical,
      children,
      onPasteImage,
      ...rest
    },
    ref,
  ) => {
    const {t} = useTranslation();
    const {theme, isDarkMode} = useTheme();

    const memoizedStyle = useMemo(() => {
      return [
        styles.textInput,
        multiline && styles.multiline,
        style,
        {
          color: theme.text.neutral[rest.editable ? 'default' : 'disabled'],
          textAlignVertical,
        },
      ];
    }, [
      multiline,
      style,
      textAlignVertical,
      rest.editable,
      theme.text.neutral,
    ]);

    const pasteImageLabel = useMemo(() => {
      return t('general.paste');
    }, [t]);

    return !useBottomSheetTextInput ? (
      <RNTextInput
        ref={ref}
        cursorColor={theme.text.neutral.default}
        placeholderTextColor={theme.text.neutral.lighter}
        multiline={multiline}
        style={memoizedStyle}
        keyboardAppearance={isDarkMode ? 'dark' : 'light'}
        {...(pasteImageLabel ? {pasteImageLabel} : {})}
        {...(onPasteImage ? {onPasteImage} : {})}
        {...rest}>
        {children}
      </RNTextInput>
    ) : (
      <BottomSheetTextInput
        // eslint-disable-next-line @typescript-eslint/ban-ts-comment
        //@ts-expect-error
        ref={ref}
        cursorColor={theme.text.neutral.default}
        placeholderTextColor={theme.text.neutral.lighter}
        multiline={multiline}
        style={memoizedStyle}
        keyboardAppearance={isDarkMode ? 'dark' : 'light'}
        {...rest}
      />
    );
  },
);

export type TextInputType = RNTextInput;
