import PropTypes from 'prop-types'
import {Container, Typography, Box, Divider, Chip} from '@mui/material'
import ArrowCircleDownIcon from '@mui/icons-material/ArrowCircleDown'

import HeadLayout from '../components/head-layout'
import Footer from '../components/footer'
import RezoDialog from '../components/rezo/rezo-dialog'
import DenyeTeks from '../components/teks/denye-teks'
import {jwennDenyeTeks} from '../lib/oki-api'

import Custom500 from './500'

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

  return (
    <HeadLayout tab={0}>
      <Box sx={{display: 'flex', flexDirection: 'column', minHeight: '100vh'}}>
        <Box sx={{flexGrow: 1, marginBottom: 4}}>
          <Container sx={{marginBottom: 2}} align='center'>
            <Typography sx={{fontWeight: 'bold'}} variant='h6' component='h1'>
              #OKi
            </Typography>
            <Typography sx={{fontWeight: 'bold'}} variant='h6' component='h2'>
              Organisation KA Internationale
            </Typography>
            <Typography sx={{fontStyle: 'italic'}} variant='caption' component='h3'>
              Paroles, traductions et Fediverse
            </Typography>
          </Container>
          <Container align='center'>
            <RezoDialog />
          </Container>
        </Box>
        <Container sx={{flexGrow: 100}}>
          <Divider variant='middle' sx={{marginBottom: 1}}>
            <Chip sx={{fontWeight: 'bold'}} color='primary' icon={<ArrowCircleDownIcon />} label='Derniers textes publiés ' variant='outlined' />
          </Divider>
          <DenyeTeks denyeTeks={teks} />
        </Container>
        <Footer />
      </Box>
    </HeadLayout>
  )
}

export async function getServerSideProps() {
  let denyeTeks
  let errorCode
  let errorMessage

  try {
    denyeTeks = await jwennDenyeTeks()
  } catch (error) {
    errorMessage = error.message
    errorCode = true
  }

  return {
    props: {
      errorCode: errorCode || null,
      errorMessage: errorMessage || null,
      teks: denyeTeks || null
    }
  }
}

Home.defaultProps = {
  errorCode: null,
  errorMessage: null,
  teks: null
}

Home.propTypes = {
  errorCode: PropTypes.bool,
  errorMessage: PropTypes.string,
  teks: PropTypes.array
}
