import React, { useRef, useEffect, useState } from 'react';
import TextareaAutosize from 'react-textarea-autosize';
import { useField } from '@unform/core';
import { ITextareaProps } from '../Textarea.interface';
import Style from './Textarea.style';

export const Textarea: React.FunctionComponent<ITextareaProps> = ({ name, title, disabled, theme, ...rest }) => {
   const inputRef = useRef(null);
   const { registerField, defaultValue = '', error, fieldName } = useField(name);
   const [focus, setFocus] = useState(false);

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

   return (
      <Style themeInput={theme} disabled={disabled}>
         <div className={`input-title ${focus && 'focus'}`}>{title}</div>
         <TextareaAutosize
            ref={inputRef}
            defaultValue={defaultValue}
            onBlur={(ev) => {
               if (rest.onBlur) rest.onBlur(ev);
               setFocus(false);
            }}
            onFocus={(ev) => {
               if (rest.onFocus) rest.onFocus(ev);
               setFocus(true);
            }}
            disabled={disabled}
            className={`${error && 'has-error'} ${focus && 'focus'} `}
            data-testid="input-textarea"
            {...(rest as any)}
         />

         {error && (
            <div data-cy={`input-error.${''}`} className="error-input" data-testid="input-error">
               {error}
            </div>
         )}
      </Style>
   );
};
