import './style.css'

import moment from 'moment-timezone'
import React, { useEffect, useState } from 'react'

interface CountdownTypes {
  startDate: string;
  timezone?: string;
  title?: string;
  message?: string;
  showMessage?: boolean;
  disableLeadingZero?: boolean;
  callback?: () => void;
  isLoggedIn?: boolean;
}

const isTimeExpired = (startDate: string, timezone: string) =>
  !moment(startDate).isAfter(moment.tz(moment(), timezone).format('YYYY-MM-DD HH:mm:ss'))

function Countdown({
  startDate,
  timezone = moment.tz.guess(),
  title = '',
  message = '',
  showMessage = false,
  disableLeadingZero = false,
  callback = () => {},
  isLoggedIn,
}: CountdownTypes) {
  const [duration, setDuration] = useState('')
  const [timeExpired, setTimeExpired] = useState(false)

  useEffect(() => {
    setTimeExpired(isTimeExpired(startDate, timezone))
  }, [])

  useEffect(() => {
    let timer: any

    if (!timeExpired) {
      timer = setInterval(() => {
        if (isTimeExpired(startDate, timezone)) {
          clearInterval(timer)
          setTimeExpired(true)
          callback()
          return
        }

        const currentDate = moment.tz(moment(), timezone).format('YYYY-MM-DD HH:mm:ss')
        const diffTime = moment(startDate).diff(currentDate)
        const duration = moment.duration(diffTime)
        const dateArr: any = {
          year: duration.years(),
          month: duration.months(),
          day: duration.days(),
          hour: duration.hours(),
          minute: duration.minutes(),
          second: duration.seconds(),
        }
        let timeLeft = ''

        for (const date in dateArr) {
          const unit = dateArr[date] === 1 ? date : date + 's'
          let val = dateArr[date]

          if (!disableLeadingZero && String(dateArr[date]).length === 1) {
            val = '0' + dateArr[date]
          }

          if (timeLeft) {
            timeLeft += `, ${val} ${unit}`
          } else if (dateArr[date]) {
            timeLeft += `${val} ${unit}`
          }
        }

        setDuration(timeLeft)
      }, 1000)
    }
    return () => {
      clearInterval(timer)
    }
  }, [timeExpired])

  return (
    <>
      {!timeExpired && duration && (
        <div className={`countdown ${!isLoggedIn ? 'countdown-on-bottom' : ''}`}>
          <div>
            <p className="title">{title}</p>
            <p>{duration}</p>
          </div>
          {showMessage && <p className="message">{message}</p>}
        </div>
      )}
    </>
  )
}

export default Countdown
