import {useCallback, useEffect, useState, forwardRef} from 'react'
import PropTypes from 'prop-types'
import axios from 'axios'
import {
  TextField,
  Container,
  Button,
  Snackbar,
  LinearProgress,
  Typography
} from '@mui/material'
import MuiAlert from '@mui/material/Alert'

const API_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:1337'

const Alert = forwardRef(function Alert(props, ref) {
  return <MuiAlert ref={ref} elevation={6} variant='filled' {...props} />
})
function EkriKomante({session, teks, meteEsKomanteOuve}) {
  const {jwt, user} = session
  const {_id} = teks
  const [komante, meteKomante] = useState({kontni: ''})
  const [ere, meteEre] = useState('')
  const [sikse, meteSikse] = useState('')
  const [chaje, meteChaje] = useState(false)
  const [esOuve, meteEsOuve] = useState(false)

  const handleClick = () => {
    meteChaje(true)
    const {kontni} = komante

    if (kontni === '') {
      meteEre({mesaj: 'Champ obligatoire'})
      meteChaje(false)

      return
    }

    const headers = {
      'content-type': 'application/json',
      Authorization: `Bearer ${jwt}`
    }

    axios.post(`${API_URL}/komante`, {
      kontni,
      teks: _id,
      user: user._id
    }, {
      headers
    })
      .then(() => {
        meteSikse('Commentaire envoyé avec succès. Il apparaîtra sur le site après validation.')
        meteChaje(false)
      })
      .catch(error => {
        meteEre(error)
        meteChaje(false)
      })
  }

  const handleUpdate = useCallback(update => {
    meteKomante({...komante, ...update})
  }, [komante])

  const handleClose = (event, reason) => {
    if (reason === 'clickaway') {
      return
    }

    meteEsOuve(false)
    meteSikse('')
    meteEre('')
    meteEsKomanteOuve(false)
  }

  const handleReset = () => {
    meteKomante({kontni: ''})
  }

  useEffect(() => {
    if (sikse) {
      meteEsOuve(true)
      handleReset()
    }
  }, [sikse])

  useEffect(() => {
    if (ere) {
      meteEsOuve(true)
    }
  }, [ere])

  return (
    <Container maxWidth='sm'>
      <form noValidate autoComplete='off'>
        <TextField
          fullWidth
          multiline
          required
          helperText='Votre commentaire (obligatoire)'
          style={{marginTop: '1em'}}
          id='komante'
          label='Kòmantè'
          value={komante.kontni}
          rows={8}
          variant='outlined'
          onChange={event => handleUpdate({kontni: event.target.value})}
        />
      </form>
      <div>
        <Button
          fullWidth
          disabled={chaje || komante.komante === ''}
          style={{marginBlock: 20}}
          variant='contained'
          color='primary'
          onClick={handleClick}
        >
          <Typography style={{fontWeight: 'bold'}}>
            Valider
          </Typography>
        </Button>
        {chaje && <LinearProgress size={24} style={{width: '100%', marginBlock: '1em'}} />}
      </div>
      {sikse && (
        <Snackbar open={esOuve} autoHideDuration={3000} onClose={handleClose}>
          <Alert severity='success' onClose={handleClose}>
            <strong>{sikse}</strong>
          </Alert>
        </Snackbar>
      )}
      {ere && (
        <Snackbar open={esOuve} autoHideDuration={3000} onClose={handleClose}>
          <Alert severity='error' onClose={handleClose}>
            <strong>Une erreur s’est produite</strong> : <i>{ere.mesaj}</i>
          </Alert>
        </Snackbar>
      )}
    </Container>
  )
}

EkriKomante.propTypes = {
  session: PropTypes.object.isRequired,
  teks: PropTypes.object.isRequired,
  meteEsKomanteOuve: PropTypes.func.isRequired
}

export default EkriKomante

