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'
import Custom500 from '../500'

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

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

  const {attributes} = anAwtis
  const {photo} = attributes

  const formatKouveti = () => {
    if (!photo?.data?.attributes) {
      return null
    }

    if (photo.data.attributes && photo.data.attributes.formats && photo.data.attributes.formats.large) {
      return photo.data.attributes.formats.large
    }

    if (photo.data.attributes && photo.data.attributes.formats && photo.data.attributes.formats.medium) {
      return photo.data.attributes.formats.medium
    }

    if (photo.data.attributes && photo.data.attributes.formats && photo.data.attributes.formats.small) {
      return photo.data.attributes.formats.small
    }

    return photo.data.attributes
  }

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

export async function getServerSideProps({query}) {
  const {slug} = query
  let anAwtis
  let error404
  let errorCode
  let errorMessage

  try {
    anAwtis = await jwennAwtisEpiSlug(slug)
  } catch (error) {
    errorMessage = error.message
    errorCode = true
  }

  if (!anAwtis) {
    error404 = true
  }

  return {
    props: {
      error404: error404 || null,
      errorCode: errorCode || null,
      errorMessage: errorMessage || null,
      anAwtis: anAwtis || null
    }
  }
}

SlugAwtis.defaultProps = {
  anAwtis: null,
  error404: null,
  errorCode: null,
  errorMessage: null,
}

SlugAwtis.propTypes = {
  error404: PropTypes.bool,
  errorCode: PropTypes.bool,
  errorMessage: PropTypes.string,
  anAwtis: PropTypes.object
}
