import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';

/* eslint consistent-return: 0 */

const CountNumber = ({ end, start = 0, increase = true, delay = 0 }) => {
  const [counter, setCounter] = useState(start);

  useEffect(() => {
    if (counter !== end) {
      let delayTimer = delay;
      if (increase && end - counter < 10) {
        delayTimer = 50;
      }
      const timer = setTimeout(() => {
        setCounter(increase ? counter + 1 : counter - 1);
      }, delayTimer);
      return () => clearTimeout(timer);
    }
  }, [counter, end, increase, delay]);

  return <>{counter}</>;
};

CountNumber.propTypes = {
  end: PropTypes.number,
  start: PropTypes.number,
  increase: PropTypes.bool,
  delay: PropTypes.number,
};

export default CountNumber;
