import { css } from '@emotion/css'
import { useTypedQuery } from '@inject/graphql/graphql'
import { GetExerciseTimeLeft } from '@inject/graphql/queries'
import { memo, useEffect, useRef } from 'react'

const wrapper = css`
  min-width: 8ch;
  font-family: Arial, monospace;
  user-select: none;
  display: flex;
  justify-content: center;
`

const timeToTimer = (res: number) =>
  new Date(res * 1000).toISOString().substring(11, 19)

const TimeLeft = () => {
  const timeLeftRef = useRef<HTMLSpanElement>(null)
  const timeLeft = useRef(0)

  useEffect(() => {
    const interval = setInterval(() => {
      timeLeft.current =
        timeLeft.current > 0 ? timeLeft.current - 1 : timeLeft.current
      if (timeLeftRef.current !== null)
        timeLeftRef.current.innerText = timeToTimer(timeLeft.current)
    }, 1000)
    return () => {
      clearInterval(interval)
    }
  }, [timeLeftRef])

  const [{ data, fetching: loading, error }, refetch] = useTypedQuery({
    query: GetExerciseTimeLeft,
    requestPolicy: 'network-only',
  })

  useEffect(() => {
    const timeout = setTimeout(() => refetch(), 60 * 1000)

    return () => {
      clearTimeout(timeout)
    }
  }, [refetch])

  useEffect(() => {
    if (data && data.exerciseTimeLeft) {
      timeLeft.current = data.exerciseTimeLeft
    }
  }, [data])

  if (loading || error || !data || data.exerciseTimeLeft === null) {
    return <span className={wrapper}>--:--:--</span>
  }

  return (
    <span className={wrapper} ref={timeLeftRef}>
      {timeToTimer(data.exerciseTimeLeft)}
    </span>
  )
}

export default memo(TimeLeft)
