import React, {
   InputHTMLAttributes,
   useCallback,
   useEffect,
   useImperativeHandle,
   useMemo,
   useRef,
   useState,
} from 'react';
import { useField } from '@unform/core';

export const SelectAutocompleteCore = React.forwardRef<InputHTMLAttributes<any>, any>(function SelectAutocompleteCore(
   props,
   inputRef: any,
) {
   const ref = useRef();
   useImperativeHandle(inputRef, () => ref.current, []);

   if (props.name) {
      return <SelectAutocompleteCoreWithUnform {...props} ref={ref} />;
   }

   return <SelectAutocompleteCoreWithoutUnform {...props} ref={ref} />;
});

export const SelectAutocompleteCoreWithUnform = React.forwardRef<InputHTMLAttributes<any>, any>(
   function SelectAutocompleteCoreWithUnform(props, inputRef: any) {
      const ref = useRef<any>();
      useImperativeHandle(inputRef, () => ref.current, []);

      const { fieldName, registerField, defaultValue = null, error, clearError } = useField(props.name);
      const [value, setValue] = useState(defaultValue);
      const inputValue = useRef<any>(defaultValue);
      // const inputValueRef = useRef(maskValue(defaultValue, props.mask, props as any));

      useEffect(() => {
         registerField({
            name: fieldName,
            ref: inputValue,
            path: 'current' as any,
            clearValue(_ref) {
               _ref.current = null;
               setValue(null);
            },
            setValue(_ref: any, value: string) {
               _ref.current = value;
               setValue(value);
            },
            getValue(_ref: any) {
               return _ref.current;
            },
         });
      }, [fieldName, registerField]);

      const onSelect = useCallback(function onSelectItem(text: any) {
         inputValue.current = text;
         setValue(text);
         if (error) clearError();
         if (props.onSelect) props.onSelect(text);
      }, [error]);

      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      return (
         <SelectAutocompleteCoreWithoutUnform
            {...props}
            ref={ref}
            onSelect={onSelect}
            value={value}
            error={error}
            defaultValue={defaultValue}
         />
      );
   },
);

export const SelectAutocompleteCoreWithoutUnform = React.forwardRef<HTMLInputElement, any>(
   function SelectAutocompleteCoreWithoutUnform(props, inputRef: any) {
      const { as, ...rest } = props;
      const ref = useRef(null);
      useImperativeHandle(inputRef, () => ref.current, []);

      const PureComponent = useMemo(() => as, [as]) as any;

      return <PureComponent {...rest} ref={ref} />;
   },
);
