import React, { useRef, useEffect, TextareaHTMLAttributes, useImperativeHandle, useCallback, useMemo } from 'react';
import { useField } from '@unform/core';
import { IPropsTextareaProps } from './TextareaCore.interface';

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

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

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

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

      const { fieldName, registerField, defaultValue = null, error, clearError } = useField(props.name);
      // const inputValueRef = useRef(maskValue(defaultValue, props.mask, props as any));

      useEffect(() => {
         registerField({
            name: fieldName,
            ref,
            path: 'current' as any,
            clearValue(_ref) {
               ref.current.value = '';
               // for native
               if (ref.current?.clear) ref.current?.clear();
            },
            setValue(_ref: any, value: string) {
               console.log(value);
               ref.current.value = value;
            },
            getValue(_ref: any) {
               return ref.current.value;
            },
         });
      }, [fieldName, registerField]);

      const onInput = useCallback(function onSelectItem(text: any) {
         // ref.current.value = text;
         if (error) clearError();
         if (props.onInput) props.onInput(text);
      }, [error]);

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

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

      const PureComponent = useMemo(() => props.as || 'input', [props.as]) as any;

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