import { useGetExerciseTimeLeft } from '@inject/graphql/queries/GetExerciseTimeLeft.generated'
import { useEffect, useState } from 'react'

const TimeLeft = () => {
  const [timeLeft, setTimeLeft] = useState(0)

  useEffect(() => {
    const interval = setInterval(
      () => setTimeLeft(prev => (prev > 0 ? prev - 1 : prev)),
      1000
    )
    return () => {
      clearInterval(interval)
    }
  }, [timeLeft])

  const { data, loading, error } = useGetExerciseTimeLeft({
    pollInterval: 60 * 1000,
  })

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

  if (loading || error || !data || data.exerciseTimeLeft === null) {
    return <></>
  }

  return (
    <span>{new Date(timeLeft * 1000).toISOString().substring(11, 19)}</span>
  )
}

export default TimeLeft
