import './style.css'

import _identity from 'lodash/identity'
import React, { memo, useState } from 'react'
import Countdown from 'react-countdown'
import ReactDOM from 'react-dom'
import SVG from 'react-inlinesvg'

import Cross from '../../assets/images/cross.svg'
import { showZero } from '../../utils/showZero'

export interface ITimerWidgetPage {
  expires_at: number;
  buyLoading?: boolean;
  onCountdownFinish?: () => void;
  container?: string;
}

export interface IRenderer {
  minutes: number;
  seconds: number;
  completed: number;
  handleCountdownFinish: () => void;
}

const TimerWidget = ({
  expires_at,
  buyLoading,
  onCountdownFinish = _identity,
  container,
}: ITimerWidgetPage) => {
  const [showTimer, setShowTimer] = useState(true)

  const handleCountdownFinish = () => {
    setShowTimer(false)
    if (!buyLoading) {
      onCountdownFinish()
    }
  }

  const renderer = ({
    minutes,
    seconds,
    completed,
    handleCountdownFinish,
  }: IRenderer) => {
    if (completed) {
      handleCountdownFinish()
      return null
    }
    return (
      <span>
        {showZero(minutes)}:{showZero(seconds)}
      </span>
    )
  }

  const hideTimer = () => {
    const timerRl: HTMLElement | null = document.querySelector('.timer')
    if (timerRl) {
      timerRl.style.visibility = 'hidden'
    }
  }

  const timerComponent = (
    <div className="timer">
      <div aria-hidden className="close-icon" onClick={hideTimer}>
        <SVG src={Cross} width="10" height="10" fill="#fff" />
      </div>
      <div className="toast-message">
        <p>Please complete your purchase before the timer reaches zero.</p>
        <p className="countdown">
          <Countdown
            date={Date.now() + expires_at * 1000}
            renderer={(props: any) =>
              renderer({
                ...props,
                handleCountdownFinish,
              })
            }
          />
        </p>
      </div>
    </div>
  )

  return showTimer && !!expires_at
    ? container
      ? ReactDOM.createPortal(
          timerComponent,
          document.querySelector(container) as HTMLElement
        )
      : timerComponent
    : null
}

export default memo(TimerWidget)
