import { useEffect, useState } from 'react'

/**
 * Countdown until targetDate,
 * return an array of four numbers representing the
 * number of days, hours, minutes and seconds until targetDate
 *
 */
const useCountdown = (targetDate: number) => {
  const [countDown, setCountDown] = useState(targetDate - new Date().getTime())

  useEffect(() => {
    if (countDown > 0) {
      setTimeout(() => setCountDown(countDown - 1000), 1000)
    } else {
      setCountDown(0)
    }
  }, [countDown])

  return getDaysHoursMinutesAndSeconds(countDown)
}

/**
 * Return an array of four numbers, representing the
 * numbers days, hours, minutes and seconds
 */
const getDaysHoursMinutesAndSeconds = (countDown: number) => {
  // calculate time left
  const days = Math.floor(countDown / (1000 * 60 * 60 * 24))
  const hours = Math.floor(
    (countDown % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60),
  )
  const minutes = Math.floor((countDown % (1000 * 60 * 60)) / (1000 * 60))
  const seconds = Math.floor((countDown % (1000 * 60)) / 1000)

  return [days, hours, minutes, seconds]
}

export { useCountdown }
