import React, { useRef, useEffect, useImperativeHandle } from 'react';
import { useDidUpdateEffect } from '@devesharp/react-hooks/lib/useDidUpdateEffect';
import { useField } from '@devesharp/unform-core';
import { IUnformInputProps, IUnformInputRef } from './UnformInput.interface';

export const UnformInput = React.forwardRef<IUnformInputRef, IUnformInputProps>(function UnformInput(
   props,
   inputRef: any,
) {
   const { fieldName, registerField, defaultValue = null, error, clearError } = useField(props.name);

   const ref = useRef<any>({
      value: defaultValue ?? null,
   });
   useImperativeHandle(inputRef, () => ref.current, []);

   useEffect(() => {
      if (props.onError) props.onError(error);
   }, [error]);

   useEffect(() => {
      props.onInitValue?.(defaultValue);
   }, []);

   // Não remove erro inicial
   useDidUpdateEffect(() => {
      if (error) {
         clearError();
      }
   }, [props.value]);

   useEffect(() => {
      if (props.value !== undefined) {
         ref.current.value = props.value;
      }
   }, [props.value]);

   useEffect(() => {
      if (props.value !== undefined) {
         ref.current.value = props.value;
      }
   }, []);

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

   return null;
});
