import React, { InputHTMLAttributes, useRef } from 'react';
import { OnlyNumbers } from '@devesharp/react-utils';
import { faMinusCircle } from '@fortawesome/free-solid-svg-icons/faMinusCircle';
import { faPlusCircle } from '@fortawesome/free-solid-svg-icons/faPlusCircle';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { Input } from '../Input';
import { IInputCounterCoreProps } from './InputCounter.interface';
import Style from './InputCounter.style';

export interface IInputCounterProps extends IInputCounterCoreProps {
   onEnter?: () => any;
}

export const InputCounter = React.forwardRef<any, IInputCounterProps>(function InputCounter(
   { name, title, withoutDotNumber = true, onEnter, value, onInput, ...rest }: IInputCounterProps,
   ref: any,
) {
   const input = useRef<HTMLInputElement>(null);

   function addNumber(): void {
      if (value == undefined) {
         const getValue = Number(OnlyNumbers(input.current.value as string));
         input.current.value = (getValue + 1) as any;
         if (onInput) onInput(input.current.value as string);
      } else if (onInput) {
         onInput(value + 1);
      }
   }

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

   return (
      <Style>
         <Input
            ref={input}
            {...(rest as any)}
            name={name}
            title={title}
            onEnter={onEnter}
            mask="number"
            decimals={0}
            withoutDotNumber={withoutDotNumber}
            textCenter
            value={value}
            onInput={onInput}
            prefix={
               <div className="button-action" onClick={subNumber} data-testid="sub-number">
                  <FontAwesomeIcon icon={faMinusCircle} />
               </div>
            }
            suffix={
               <div className="button-action" onClick={addNumber} data-testid="add-number">
                  <FontAwesomeIcon icon={faPlusCircle} />
               </div>
            }
         />
      </Style>
   );
});
