/* eslint-disable react/no-children-prop */
import React, { memo, useRef } from 'react';
import {
  FormControl,
  IInputProps,
  Input as InputNB,
  InputGroup as InputGroupNB,
  InputLeftAddon,
  WarningOutlineIcon,
  Text,
} from 'native-base';
import type { Mask } from '../Masks/formatWithMask.types';
import maskField from '../Masks/maskField';
import styles from './styles';

interface InputProps extends IInputProps {
  name: string;
  label: string;
  errorInfo?: string | string[];
  isRequired?: boolean;
  mask?: Mask | ((text: string) => Mask);
  initialValue?: string;
  setFieldValue: any;
  setFieldTouched: any;
  prefix: string;
  touched?: boolean;
  ErrorBox?: (errorInfo: any) => JSX.Element;
}

const InputGroup = ({
  name,
  label,
  errorInfo,
  isRequired = true,
  setFieldValue,
  prefix,
  mask,
  initialValue,
  setFieldTouched,
  touched,
  ErrorBox,
  ...rest
}: InputProps) => {
  const refValue = useRef(maskField({ text: initialValue, mask }).masked);
  const handleOnChangeText = (text: string) => {
    const { masked, unmasked } = maskField({ text, mask });
    refValue.current = masked;
    setFieldValue(name, unmasked);
  };
  return (
    <FormControl isRequired={isRequired} isInvalid={!!errorInfo && !!touched}>
      <FormControl.Label>{label}</FormControl.Label>
      <InputGroupNB>
        <InputLeftAddon
          children={<Text style={styles.prefix!.style}>{prefix}</Text>}
          {...styles.leftAddon}
        />
        {/* eslint-disable-next-line react/jsx-props-no-spreading */}
        <InputNB
          w="87%"
          onChangeText={(text) => {
            handleOnChangeText(text);
          }}
          onBlur={() => setFieldTouched(name)}
          value={refValue.current}
          {...styles.input}
          {...rest}
        />
      </InputGroupNB>
      {touched && errorInfo ? (
        ErrorBox ? (
          ErrorBox(errorInfo)
        ) : typeof errorInfo === 'string' ? (
          <FormControl.ErrorMessage leftIcon={<WarningOutlineIcon size="xs" />}>
            {errorInfo}
          </FormControl.ErrorMessage>
        ) : (
          errorInfo.map((error) => {
            return (
              <FormControl.ErrorMessage
                leftIcon={<WarningOutlineIcon size="xs" />}
              >
                {error}
              </FormControl.ErrorMessage>
            );
          })
        )
      ) : (
        <FormControl.HelperText>&nbsp;</FormControl.HelperText>
      )}
    </FormControl>
  );
};

export default memo(InputGroup);
