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

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

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

import Custom404 from '../404'
import Custom500 from '../500'

export default function Awtis({errorCode, error404, errorMessage, pajTotal, awtisPouChakPaj, paj}) {
  if (error404) {
    return <Custom404 statusCode={error404} />
  }

  if (errorCode) {
    console.log('⚠️ error', errorMessage)
    return <Custom500 statusCode={errorCode} />
  }

  return (
    <HeadLayout title='Awtis - Liste des artistes' tab={2} slug='awtis'>
      <Box sx={{display: 'flex', flexDirection: 'column', minHeight: '100vh'}}>
        <Pajinasyon pajTotal={pajTotal} paj={paj} />
        <Container sx={{marginBottom: 5, flexGrow: 100}}>
          <Grid container spacing={{xs: 2, md: 3}}>
            {awtisPouChakPaj.map(artiste => <AwtisKat key={artiste.id} artiste={artiste.attributes} />)}
          </Grid>
        </Container>
        <Footer />
      </Box>
    </HeadLayout>
  )
}

export async function getServerSideProps({query}) {
  const {paj} = query
  let error404
  let errorCode
  let errorMessage
  let awtisPouChakPaj

  const pajParsed = Array.isArray(paj) ? Number.parseInt(paj[1], 10) : Number.parseInt(paj, 10)

  try {
    awtisPouChakPaj = await jwennAwtisPajinasyon(pajParsed)
  } catch (error) {
    errorMessage = error.message
    errorCode = true
  }

  const pajTotal = Math.ceil(awtisPouChakPaj.meta.pagination.total / awtisPouChakPaj.meta.pagination.limit)

  if (pajParsed > pajTotal || pajParsed < 1) {
    error404 = true
  }

  return {
    props: {
      error404: error404 || null,
      errorCode: errorCode || null,
      errorMessage: errorMessage || null,
      pajTotal,
      awtisPouChakPaj: awtisPouChakPaj.data,
      paj: pajParsed
    }
  }
}

Awtis.defaultProps = {
  error404: null,
  errorCode: null,
  errorMessage: null,
}

Awtis.propTypes = {
  error404: PropTypes.bool,
  errorCode: PropTypes.bool,
  errorMessage: PropTypes.string,
  pajTotal: PropTypes.number.isRequired,
  awtisPouChakPaj: PropTypes.array.isRequired,
  paj: PropTypes.number.isRequired
}
