import { Timer } from '../src/timer'
import { useContext, useState, useEffect } from 'react'
import { TrainingContext } from './_app'
import { useRouter } from 'next/router'

const TimerPage = () => {
  const trainingList = useContext(TrainingContext)
  const [trainingIndex, setTrainingIndex] = useState(trainingList.length - 1)
  const router = useRouter()
  const queryId = router.query && router.query.id

  useEffect(() => {
    if (typeof queryId !== 'string') return
    const intId = parseInt(queryId)
    if (intId < 0 || intId + 1 > trainingList.length) return
    setTrainingIndex(intId)
  }, [router.query])

  const { trainings } = trainingList[trainingIndex]

  return <Timer training={trainings[0]} />
}

export default TimerPage
