import { useTrainingsQuery, usePublishedTrainingsQuery } from '../../gql'
import { useState } from 'react'
import TrainingHint from './TrainingHint'
import theme from '../../styles/theme'

const TrainingArchive = () => {
  const trainingsPerPage = 5
  const [state, setState] = useState(0)
  const archive = usePublishedTrainingsQuery()
  const { data, error, loading } = useTrainingsQuery({
    variables: { skip: state * trainingsPerPage, first: trainingsPerPage },
  })
  if (loading) return <p>Loading trainings...</p>
  if (error) return <p>Error loading trainings.</p>
  if (!data) return null
  const { trainings, count } = data
  const pages = []

  for (let index = 0; index < count.aggregate.count / trainingsPerPage; index++) {
    pages.push(index)
  }

  return (
    <section className='training-archive'>
      <h2>Training Archive</h2>
      <ol>
        {trainings.map((training) => (
          <TrainingHint key={training.id} training={training} />
        ))}
      </ol>
      {pages.map((index) => (
        <button
          key={index}
          onClick={(event) => setState(index)}
          className={index === state ? 'active' : undefined}
        >
          {index + 1}
        </button>
      ))}

      <style jsx>{`
        button {
          border: none;
          padding: 0.3em 0.6em;
          margin: 0 0.3em;
          background-color: transparent;
          color: ${theme.colors.darkblue};
          border-radius: 6px;
          cursor: pointer;
        }
        button:hover {
          background-color: ${theme.colors.darkblue}22;
        }
        button.active {
          background-color: ${theme.colors.darkblue};
          color: ${theme.colors.offWhite};
        }
      `}</style>
    </section>
  )
}

export default TrainingArchive
