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

import AwtisDetay from '../../components/awtis/awtis-detay'
import Footer from '../../components/footer'
import HeadLayout from '../../components/head-layout'
import {jwennAwtisEpiSlug} from '../../lib/oki-api'

import Custom404 from '../404'

export default function SlugAwtis({error, anAwtis}) {
  if (error) {
    return <Custom404 statusCode={error} />
  }

  const {foto} = anAwtis

  const formatKouveti = () => {
    if (foto.length === 0) {
      return null
    }

    const [anFoto] = foto

    if (anFoto && anFoto.formats && anFoto.formats.large) {
      return anFoto.formats.large
    }

    if (anFoto && anFoto.formats && anFoto.formats.medium) {
      return anFoto.formats.medium
    }

    if (anFoto && anFoto.formats && anFoto.formats.small) {
      return anFoto.formats.small
    }

    return anFoto
  }

  return (
    <HeadLayout
      imageUrl={formatKouveti() ? formatKouveti().url : null}
      imageWidth={formatKouveti() ? formatKouveti().width : null}
      imageHeight={formatKouveti() ? formatKouveti().height : null}
      imageMime={formatKouveti() ? formatKouveti().mime : null}
      title={`${anAwtis.alias} - Paroles et Traductions`} tab={2} slug={`awtis/${anAwtis.slug}`}
    >
      <Box sx={{display: 'flex', flexDirection: 'column', minHeight: '100vh'}}>
        <AwtisDetay anAwtis={anAwtis} />
      </Box>
      <Footer />
    </HeadLayout>
  )
}

export async function getServerSideProps({query}) {
  const {slug} = query
  const anAwtis = await jwennAwtisEpiSlug(slug)

  return {
    props: {
      error: Boolean(!anAwtis),
      anAwtis: anAwtis ? anAwtis : null
    }
  }
}

SlugAwtis.defaultProps = {
  anAwtis: null
}

SlugAwtis.propTypes = {
  error: PropTypes.bool.isRequired,
  anAwtis: PropTypes.object
}
