import React, { useState, useEffect } from 'react';
import { AtomButtonIcon } from 'native/atoms/Buttons/Icon';
import { AtomInputNumber } from 'native/atoms/Input/InputNumber';
import { QuantityContainer, InputContainer, ButtonContainer } from './styles';

export interface IQuantityProps {
  /** Number Input value */
  value: string;
  /** Minimum possible value */
  min?: string;
  /** Maximum value */
  max: string;
  /** Action called after click the minus button */
  onRemove: () => void;
  /** Action called after click the plus button */
  onAdd: () => void;
  /** Action called after change the input value directly */
  onChange: () => void;
}

export const MoleculeQuantityPick = ({
  value,
  min = '0',
  max,
  onRemove,
  onAdd,
  onChange
}: IQuantityProps) => {
  const [val, setVal] = useState<string>(value);
  const [numberValue, setNumberValue] = useState<number>(parseInt(value));


  const handleAdd = () => {
    let newVal = numberValue + 1;
    if (newVal <= parseInt(max)) {
      setNumberValue(newVal);
      setVal(newVal.toString())
    }
    onAdd();
  }

  const handleRemove = () => {
    let newVal = numberValue === 0 ? 0 : (numberValue - 1);

    if (newVal >= parseInt(min)) {
      setNumberValue(newVal);
      setVal(newVal.toString());
    }
    onRemove();
  }

  const handleChange = (v: number) => {
    let changedVal = isNaN(v) ? 0 : v;
    let minVal = parseInt(min);
    let maxVal = parseInt(max);

    if (changedVal >= minVal && changedVal <= maxVal) {
      setNumberValue(changedVal);
      setVal(changedVal.toString());
    } else {
      setNumberValue(minVal);
      setVal(min);
    }

    onChange();
  }

  useEffect(() => {
  }, [numberValue])

  useEffect(() => {
    handleChange(parseInt(value))
  }, [value])

  return (
    <QuantityContainer>
      <ButtonContainer>
        <AtomButtonIcon
          disabled={val === min}
          color='primary'
          typeButtonIcon={'outline'}
          icon='remove'
          text=''
          onPress={handleRemove}
          testID='quantity-remove-button'
          shape='circle'
          size='large'
          width='48px'
        />
      </ButtonContainer>
      <InputContainer>
        <AtomInputNumber
          disabled={false}
          value={val}
          onChange={handleChange}
          min={min}
          max={max}
          styles={{ textAlign: 'center' }}
        />
      </InputContainer>
      <ButtonContainer>
        <AtomButtonIcon
          disabled={val === max}
          typeButtonIcon={'outline'}
          color='primary'
          customColor='tertiary'
          icon='add'
          text=''
          onPress={handleAdd}
          testID='quantity-add-button'
          shape='circle'
          size='large'
          width='48px'
        />
      </ButtonContainer>
    </QuantityContainer>
  )
}