import PropTypes from 'prop-types'
import {Container, Grid} from '@mui/material'

import {jwennAwtisKantite, jwennAwtisPajinasyon} from '../../lib/oki-api'

import AwtisKat from '../../components/awtis/awtis-kat'
import Pajinasyon from '../../components/awtis/pajinasyon'
import HeadLayout from '../../components/head-layout'

const AWTIS_POU_CHAK_PAJ = process.env.NEXT_PUBLIC_AWTIS_POU_CHAK_PAJ || 6

export default function Awtis({pajTotal, awtisPouChakPaj, paj}) {
  return (
    <HeadLayout title='Awtis - Liste des artistes' tab={2} slug='awtis'>
      <Pajinasyon pajTotal={pajTotal} paj={paj} />
      <Container>
        <Grid container spacing={{xs: 2, md: 3}}>
          {awtisPouChakPaj.map(anAwtis => <AwtisKat key={anAwtis.id} anAwtis={anAwtis} />)}
        </Grid>
      </Container>
    </HeadLayout>
  )
}

Awtis.propTypes = {
  pajTotal: PropTypes.number.isRequired,
  awtisPouChakPaj: PropTypes.array.isRequired,
  paj: PropTypes.number.isRequired
}

export async function getServerSideProps({query}) {
  const {paj} = query

  const pajParsed = Array.isArray(paj) ? Number.parseInt(paj[1], 10) : Number.parseInt(paj, 10)
  const awtisPouChakPaj = await jwennAwtisPajinasyon(pajParsed)
  const awtisCountRequest = await jwennAwtisKantite()
  const awtisCount = Number.parseInt(awtisCountRequest, 10)
  const pajTotal = Math.ceil(awtisCount / AWTIS_POU_CHAK_PAJ)

  if (pajParsed > pajTotal) {
    throw new Error('Pa twouvé paj-la')
  }

  return {
    props: {
      pajTotal,
      awtisPouChakPaj,
      paj: pajParsed
    }
  }
}
