import { useEffect, useState } from 'react'

const CountDown = ({ initialTime }) => {
  const days = Math.floor(initialTime / 86400)
  const hours = Math.floor((initialTime % 86400) / 3600)
  const minutes = Math.floor((initialTime % 3600) / 60)
  const seconds = initialTime % 60

  const [timeLeft, setTimeLeft] = useState({
    day: days,
    hour: hours,
    minute: minutes,
    second: seconds
  })

  useEffect(() => {
    const timer = setInterval(() => {
      const totalSeconds = timeLeft.day * 86400 + timeLeft.hour * 3600 + timeLeft.minute * 60 + timeLeft.second
      const secondsLeft = totalSeconds - 1
      if (secondsLeft < 0) {
        clearInterval(timer)
      } else {
        const days = Math.floor(secondsLeft / 86400)
        const hours = Math.floor((secondsLeft % 86400) / 3600)
        const minutes = Math.floor((secondsLeft % 3600) / 60)
        const seconds = secondsLeft % 60
        setTimeLeft({ day: days, hour: hours, minute: minutes, second: seconds })
      }
    }, 1000)
    return () => clearInterval(timer)
  }, [timeLeft])

  return (
    <div className='flex gap-x-2.5 w-fit'>
      <div className='flex flex-col items-center'>
        <span className='bg-red-600 text-white font-semibold w-10 h-10 flex items-center justify-center rounded'>{timeLeft.day.toString().padStart(2, '0')}</span>
        <span className='text-caption-1 text-gray-700 mt-1'>Hari</span>
      </div>
      <div className='flex flex-col items-center'>
        <span className='bg-red-600 text-white font-semibold w-10 h-10 flex items-center justify-center rounded'>{timeLeft.hour.toString().padStart(2, '0')}</span>
        <span className='text-caption-1 text-gray-700 mt-1'>Jam</span>
      </div>
      <div className='flex flex-col items-center'>
        <span className='bg-red-600 text-white font-semibold w-10 h-10 flex items-center justify-center rounded'>{timeLeft.minute.toString().padStart(2, '0')}</span>
        <span className='text-caption-1 text-gray-700 mt-1'>Menit</span>
      </div>
      <div className='flex flex-col items-center'>
        <span className='bg-red-600 text-white font-semibold w-10 h-10 flex items-center justify-center rounded'>{timeLeft.second.toString().padStart(2, '0')}</span>
        <span className='text-caption-1 text-gray-700 mt-1'>Detik</span>
      </div>
    </div>
  )
}

export default CountDown
