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

/* eslint-disable react/jsx-one-expression-per-line, operator-assignment, consistent-return */

const CountDate = ({ targetDate }) => {
  const [counter, setCounter] = useState(targetDate);
  const second = 1000;

  // Seconds between now and target
  const currentDate = new Date().getTime();
  let secondsLeft = (targetDate - currentDate) / second;

  // 60 x 60 x 24
  const days = parseInt(secondsLeft / 86400);
  secondsLeft = secondsLeft % 86400;

  const hours = parseInt(secondsLeft / 3600);
  secondsLeft = secondsLeft % 3600;

  const minutes = parseInt(secondsLeft / 60);
  // Leftover
  const seconds = parseInt(secondsLeft % 60);

  useEffect(() => {
    if (targetDate > currentDate) {
      const countDown = setTimeout(() => {
        setCounter(counter + 1);
      }, second);
      return () => clearTimeout(countDown);
    }
  }, [counter, currentDate, targetDate]);

  return (
    <span>
      {days !== 0 && <span>{days} D, </span>}
      {hours} h : {minutes} m : {seconds} s
    </span>
  );
};

CountDate.propTypes = {
  targetDate: PropTypes.number.isRequired,
};

export default CountDate;
