import Link from 'next/link'
import { Training } from '../src/training'
import { useContext, useState, useEffect } from 'react'
import { TrainingContext } from './_app'
import TrainingArchive from '../src/training/components/TrainingArchive'
import { useRouter } from 'next/router'

const Home = () => {
  //const { data, error, loading } = useTrainingsQuery();
  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 (
    <>
      <section className='training-meta'>
        <h1>Stay in Shape with u-fit</h1>
        <p>u-fit is a high intensity interval training offered by u-blox.</p>
        <aside>
          <div className='info'>
            <span className='caption'>When</span>
            <span className='data'>Tuesdays, 11:45-12:30</span>
          </div>
          <div className='info'>
            <span className='caption'>Equipment</span>
            <span className='data'>Towel, water, optional: yoga mat</span>
          </div>
        </aside>
      </section>

      <section id='nextTraining'>
        <Training index={trainingIndex} training={trainings[0]} />
      </section>

      <TrainingArchive />

      <style jsx>
        {`
          .training-meta {
            padding: 0 1em;
          }
          .info .caption {
            display: inline-block;
            font-weight: 900;
            min-width: 6rem;
          }
        `}
      </style>
    </>
  )
}

export default Home
