import React, { useRef, useEffect, useState, useImperativeHandle, useContext } from 'react';
import { useField } from '@unform/core';
import { OnlyNumbers } from '../../../services';
import AppContext from '../../AppProvider/AppContext';
import { maskValue } from '../../MaskText/mask.utils';
import { IPropsInput } from '../input.interface';
import { Container } from './Input.style';
import { InputPure } from './InputPure';

export const Input = React.forwardRef<any, IPropsInput>(function Input(props: IPropsInput, ref: any) {
   props = { decimals: 0, ...props };

   const {
      name,
      title,
      textRight = false,
      textCenter = false,
      prefix,
      decimals = 0,
      theme: themeInput,
      suffix,
      loading = false,
      onEnter = () => {},
      as = InputPure,
      number = false,
      withoutDotNumber = false,
      CEP = false,
      CNPJ = false,
      CPF = false,
      RG = false,
      phone = false,
      noSpaces = false,
      password = false,
      ...rest
   } = props;

   // Custom component
   const { pureComponents: { Input: InputComponent = null } = {} } = useContext(AppContext);
   const Component = InputComponent ?? as;

   const inputRef = useRef<any>();

   useImperativeHandle(ref, () => inputRef.current, [inputRef]);

   // Unform
   const { registerField, defaultValue = '', error, fieldName, clearError } = useField(name);
   const defaultValueInput = maskValue(defaultValue, props);

   // Se Input está em focus
   const [focus, setFocus] = useState(false);
   const [value, setValue] = useState(defaultValueInput);

   const [hidePassword, setHidePassword] = useState(true);

   useEffect(() => {
      registerField({
         name: fieldName,
         ref: inputRef.current,
         path: 'value' as any,
         clearValue(_ref) {
            _ref.value = '';
            _ref.clear();
         },
         setValue(_ref: any, v: string) {
            inputRef.current.value = maskValue(v, props);
            _ref.setNativeProps({ text: inputRef.current.value });
         },
         getValue(_ref: any) {
            if (number) return OnlyNumbers(_ref.value);
            if (CEP) return OnlyNumbers(_ref.value);
            return _ref.value;
         },
      });
   }, [fieldName, registerField]);

   return (
      <Container>
         <Component
            {...props}
            error={error}
            inputRef={inputRef}
            defaultValueInput={defaultValueInput}
            hidePassword={hidePassword}
            value={value}
            setValue={setValue}
            focus={focus}
            setFocus={setFocus}
            clearError={clearError}
            setHidePassword={setHidePassword}
         />
      </Container>
   );
});
