import React, { memo, useRef } from 'react';
import {
  FormControl,
  IInputProps,
  Input as InputNB,
  WarningOutlineIcon,
  useToast,
  Icon,
} from 'native-base';
import type { Mask } from '../Masks/formatWithMask.types';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import maskField from '../Masks/maskField';
import styles from './styles';

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

const InputWithHelp = ({
  message,
  name,
  label,
  errorInfo,
  isRequired = true,
  mask,
  initialValue,
  setFieldValue,
  setFieldTouched,
  touched,
  ErrorBox,
  ...rest
}: InputProps) => {
  const toast = useToast();

  const refValue = useRef(maskField({ text: initialValue, mask }).masked);
  const handleOnChangeText = (text: string) => {
    const { masked, unmasked } = maskField({ text, mask });
    refValue.current = masked;
    setFieldValue(name, unmasked);
  };
  console.log('Render: ', name, ' Error: ', errorInfo);
  return (
    <FormControl isRequired={isRequired} isInvalid={!!errorInfo && !!touched}>
      <FormControl.Label>{label}</FormControl.Label>
      <InputNB
        onChangeText={handleOnChangeText}
        value={refValue.current}
        InputRightElement={
          <Icon
            as={MaterialIcons}
            name="help"
            style={styles.iconHelp!.style}
            onPress={() =>
              toast.show({
                description: message,
                placement: 'top',
                duration: 2000,
              })
            }
          />
        }
        onBlur={() => setFieldTouched(name)}
        {...rest}
      />
      {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(InputWithHelp);
