import React, { FC, ReactNode, useState } from 'react';
import {
  TextInput,
  Text,
  View,
  InputModeOptions,
  NativeSyntheticEvent,
  TextInputFocusEventData
} from 'react-native';
import { styling } from './style';
import { Colors } from 'src/theme';

type Props = {
  placeholder?: string;
  onChange?: (text: string) => void;
  header?: string;
  isPrivate?: boolean;
  inputMode?: InputModeOptions;
  isFocused?: (boolean: boolean) => void;
  value?: string;
  active?: boolean;
  onBlur?: (e: NativeSyntheticEvent<TextInputFocusEventData>) => void;
  formikError?: string | boolean;
  icon?: ReactNode;
  multiline?: boolean;
  editable?: boolean;
  height?: number;
  backgroundColor?: string;
};

export const Input: FC<Props> = ({
  onChange,
  placeholder,
  header,
  isPrivate,
  inputMode,
  isFocused,
  onBlur,
  value,
  formikError,
  icon,
  multiline,
  editable,
  height,
  backgroundColor = Colors.FILL_LIGHT
}) => {
  const [focused, setFocused] = useState(false);

  const styles = styling(focused);

  return (
    <View>
      {header ? <Text style={styles.text}>{header}</Text> : null}
      <View
        style={[
          [styles.wrapper, formikError ? styles.inputError : null, { backgroundColor }],
          { flexDirection: 'row', alignItems: 'center' },
          multiline ? { height: height ?? 100 } : { height: height ?? 44 }
        ]}
      >
        {icon ? (
          <View
            style={{
              height: 44,
              width: 44,
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center'
            }}
          >
            {icon}
          </View>
        ) : null}
        <TextInput
          editable={editable}
          value={value}
          inputMode={inputMode ?? 'text'}
          secureTextEntry={isPrivate ?? false}
          placeholder={placeholder}
          onChangeText={onChange}
          multiline={multiline}
          onFocus={() => {
            setFocused(true);
            if (isFocused) {
              isFocused(true);
            }
          }}
          onBlur={(e) => {
            setFocused(false);
            if (onBlur) {
              onBlur(e);
            }
          }}
          style={[{ height: '100%', width: '100%' }, !icon ? { padding: 10 } : null]}
        />
      </View>
      {formikError ? <Text style={styles.errorText}>{formikError}</Text> : null}
    </View>
  );
};