import { formatTime } from '../../training/utils'
import { useEffect, useState, useRef } from 'react'
import { Howl } from 'howler'
import { describeArc, limit } from '../utils'

interface ICountdown {
  seconds: number
  totalPercent: number
  exercisePercent: number
  onClick: () => void
}

const Countdown = ({
  seconds,
  totalPercent,
  exercisePercent,
  onClick
}: ICountdown) => {
  const [color, setColor] = useState('rgba(55,55,55,1)')
  const [intSeconds, setIntSeconds] = useState(0)

  useEffect(() => {
    setIntSeconds(Math.ceil(seconds))
  }, [seconds])

  useEffect(() => {
    if (intSeconds <= 5) {
      fadeIn()
      setTimeout(fadeOut, 300)
    }
  }, [intSeconds])

  function fadeIn() {
    setColor('rgba(127,0,0,1)')
  }
  function fadeOut() {
    setColor('rgba(55,55,55,1)')
  }

  return (
    <div id='timer' style={{ color }} onClick={onClick}>
      <svg>
        <text
          textAnchor='middle'
          alignmentBaseline='central'
          y='185'
          x='150'
          fill={color}
        >
          {formatTime(intSeconds)}
        </text>
        <circle
          cx='150'
          cy='150'
          r='140'
          fill='none'
          stroke='#aa333344'
          strokeWidth='5'
        />
        <circle
          cx='150'
          cy='150'
          r='130'
          fill='none'
          stroke='#3333aa44'
          strokeWidth='5'
        />
        <path
          d={describeArc(150, 150, 140, 0, limit(totalPercent * 360, 0, 359))}
          fill='none'
          stroke='#aa3333ff'
          strokeWidth='8'
        />
        <path
          d={describeArc(
            150,
            150,
            130,
            0,
            limit(exercisePercent * 360, 0, 359)
          )}
          fill='none'
          stroke='#3333aaff'
          strokeWidth='8'
        />
      </svg>

      <style jsx>
        {`
          :global(#timer svg) {
            width: 300px;
            height: 300px;
            font-size: 100px;
            font-weight: 900;
            transition: color 300ms ease-out;
            cursor: pointer;
          }
        `}
      </style>
    </div>
  )
}

export default Countdown
