import React, { useState, useEffect } from 'react'
import PropTypes from 'prop-types'
import { css } from '@emotion/css'
import bg from '../../static/images/bg.png'

const FlashSale = (props) => {
  const { data = {}, marginBottom = 0 } = props

  if (!data || (!data.endDate && data.timeleft == '0')) {
    return null
  }

  const {
    endDate = '',
    timeleft = '',
    repeat = 0,
    backgroundColor = '#705EF9',
    text = 'ราคาพิเศษ⚡จะหมดใน',
    fontColor = '#FFFFFF',
  } = data

  const getDeadTime = () => {
    if (endDate) {
      // custom date
      return endDate
    } else {
      // fake date
      let deadline = new Date()
      const time = timeleft ? timeleft : 0
      deadline.setHours(deadline.getHours() + parseInt(time))

      return deadline
    }
  }

  const getTimeRemaining = (time) => {
    const total = Date.parse(time) - Date.parse(new Date())
    const days = String(Math.floor(total / (1000 * 60 * 60 * 24))).padStart(2, 0)
    const hours = String(Math.floor((total / 1000 / 60 / 60) % 24)).padStart(2, 0)
    const minutes = String(Math.floor((total / 1000 / 60) % 60)).padStart(2, 0)
    const seconds = String(Math.floor((total / 1000) % 60)).padStart(2, 0)

    return {
      total,
      days,
      hours,
      minutes,
      seconds,
    }
  }

  const init = getDeadTime()
  const [timer, setTimer] = useState(getTimeRemaining(init))
  const [finish, setFinish] = useState(false)
  const [repeatCountdown, setRepeatCountdown] = useState(0)

  useEffect(() => {
    const time = getDeadTime()
    const id = setInterval(() => {
      let { total, days, hours, minutes, seconds } = getTimeRemaining(time)

      if (total >= 0) {
        setTimer({ days, hours, minutes, seconds })
      } else {
        // hide for end-date
        setFinish(true)

        // Set repeat countdown
        if (repeatCountdown < repeat) {
          setRepeatCountdown(repeatCountdown + 1)
        }

        // stop interval
        clearInterval(id)
      }
    }, 1000)

    return () => clearInterval(id)
  }, [repeatCountdown])

  const countdown = [
    {
      title: 'วัน',
      value: timer.days,
    },
    {
      title: 'ชั่วโมง',
      value: timer.hours,
    },
    {
      title: 'นาที',
      value: timer.minutes,
    },
    {
      title: 'วินาที',
      value: timer.seconds,
    },
  ]

  // hide flash sale when end-date finish
  if (repeat == 0 && finish) {
    return null
  }

  return (
    <div
      className={`
    ${css`
      margin-bottom: ${marginBottom}px;
      background: ${backgroundColor};
      width: 100%;
      height: 200px;
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
    `}`}
    >
      <p
        className={`${css`
          color: ${fontColor};
          font-family: 'Kanit', sans-serif;
          font-size: 24px;
          font-weight: 600;
        `}`}
      >
        {text}
      </p>

      <div
        className={`${css`
          display: flex;
        `}`}
      >
        {countdown.map((item, index) => (
          <div
            className={`${css`
              text-align: center;
              color: #ffffff;
              margin: 0px 20px;
              position: relative;
            `}`}
            key={index}
          >
            <div
              className={`${css`
                width: 48px;
                height: 48px;
                background: #ffffff;
                border-radius: 14px;
                display: flex;
                justify-content: center;
                align-items: center;
                box-shadow: 7px 7px rgba(255, 255, 255, 0.2);
              `}`}
            >
              <p
                className={`${css`
                  font-size: 24px;
                  font-weight: 400;
                  color: #ed1e46;
                  z-index: 10;
                  font-family: 'Kanit', sans-serif;
                `}`}
              >
                {item.value}
              </p>
              <img
                src={bg}
                className={`${css`
                  min-width: 80px;
                  width: 80px;
                  opacity: 0.3;
                  position: absolute;
                  top: -20px;
                `}`}
              />
            </div>
            <p
              className={`${css`
                margin-top: 15px;
                font-family: 'Kanit', sans-serif;
                font-size: 16px;
                color: #ffffff;
              `}`}
            >
              {item.title}
            </p>
          </div>
        ))}
      </div>
    </div>
  )
}

FlashSale.propTypes = {
  data: PropTypes.shape({
    endDate: PropTypes.string,
    timeleft: PropTypes.string,
    repeat: PropTypes.number,
    backgroundColor: PropTypes.string,
    text: PropTypes.string,
    fontColor: PropTypes.string,
  }),
  marginBottom: PropTypes.number,
}

FlashSale.defaultProps = {
  data: {
    endDate: '',
    timeleft: '0',
    repeat: 0,
    backgroundColor: '#705EF9',
    text: 'ราคาพิเศษ⚡จะหมดใน',
    fontColor: '#FFFFFF',
  },
  marginBottom: 0,
}

export default FlashSale
