import PropTypes from 'prop-types'

import {jwennDenyeTeks, jwennTeks} from '../../lib/oki-api'

import TeksDrawer from '../../components/teks/teks-drawer'
import HeadLayout from '../../components/head-layout'

import Custom500 from '../500'

export default function Teks({errorCode, errorMessage, paroles, denyeTeks}) {
  if (errorCode) {
    console.log('⚠️ error', errorMessage)
    return <Custom500 />
  }

  return (
    <HeadLayout title='Paroles et Traductions' tab={1} slug='paroles'>
      <TeksDrawer paroles={paroles} denyeTeks={denyeTeks} />
    </HeadLayout>
  )
}

export async function getServerSideProps() {
  let paroles
  let denyeTeks
  let hasError
  let errorMessage

  try {
    paroles = await jwennTeks()
    denyeTeks = await jwennDenyeTeks()
  } catch (error) {
    errorMessage = error.message
    hasError = true
  }

  return {
    props: {
      errorCode: hasError || null,
      errorMessage: errorMessage || null,
      paroles: paroles || null,
      denyeTeks: denyeTeks || null
    }
  }
}

Teks.defaultProps = {
  errorCode: null,
  errorMessage: null,
  paroles: null,
  denyeTeks: null
}

Teks.propTypes = {
  errorCode: PropTypes.bool,
  errorMessage: PropTypes.string,
  paroles: PropTypes.array,
  denyeTeks: PropTypes.array
}
