import { useTrainingArchiveQuery } from '../../gql'
import { useState } from 'react'
import TrainingHint from './TrainingHint'
import theme from '../../styles/theme'

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

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

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

      <style jsx>{`
        ul {
          display: grid;
          grid-template-columns: 1fr;
          list-style: none;
          margin: 1.2em 0;
          padding: 0;
        }
        ul :global(a) {
          text-decoration: none;
          color: ${theme.colors.color};
        }
        button {
          display: inline;
          border: none;
          padding: 0.3em 0.6em;
          margin: 0 0.3em;
          background-color: transparent;
          color: ${theme.colors.buttonBackground};
          border-radius: 6px;
          cursor: pointer;
        }
        button:hover {
          background-color: ${theme.colors.buttonBackground}22;
        }
        button.active {
          background-color: ${theme.colors.buttonBackground};
          color: ${theme.colors.button};
        }
        @media (min-width: ${theme.midsize}) {
          ul {
            grid-template-columns: 1fr 1fr;
          }
        }
        @media (min-width: ${theme.fullsize}) {
          ul {
            grid-template-columns: repeat(4, 1fr);
          }
        }
      `}</style>
    </section>
  )
}

export default TrainingArchive
