import React, { useRef, useEffect, useState, useImperativeHandle } from 'react';
import { useField } from '@unform/core';
import { useEventListener } from '../../../hooks/useEventListener';
import { OnlyNumbers } from '../../../services/utils.service';
import { Input } from '../../Input/web';
import { maskValue } from '../../MaskText/mask.utils';
import { IPropsInput } from '../InputCounter.interface';
import Style from './InputCounter.style';

interface IPropsInputWeb extends IPropsInput {
   onEnter?: () => any;
}

export const InputCounter = React.forwardRef<any, IPropsInputWeb>(function InputCounter(
   { name, title, onEnter }: IPropsInputWeb,
   ref: any,
) {
   const input = useRef<HTMLInputElement>();

   function addNumber(): void {
      const value = Number(OnlyNumbers(input.current.value));
      input.current.value = (value + 1) as any;
   }

   function subNumber(): void {
      const value = Number(OnlyNumbers(input.current.value));
      input.current.value = (value <= 0 ? 0 : value - 1) as any;
   }

   return (
      <Style>
         <Input
            ref={input}
            name={name}
            title={title}
            onEnter={onEnter}
            number
            withoutDotNumber
            textCenter
            prefix={
               <div className="button-action" onClick={subNumber} data-testid="sub-number">
                  <i className="fas fa-minus-circle" />
               </div>
            }
            suffix={
               <div className="button-action" onClick={addNumber} data-testid="add-number">
                  <i className="fas fa-plus-circle" />
               </div>
            }
         />
      </Style>
   );
});
