import {useState, forwardRef} from 'react'
import PropTypes from 'prop-types'
import axios from 'axios'
import {useRouter} from 'next/router'

import {FormControl, Snackbar, IconButton, Button, Input, InputAdornment, InputLabel, Box, Container, Typography, LinearProgress} from '@mui/material'
import MuiAlert from '@mui/material/Alert'
import Visibility from '@mui/icons-material/Visibility'
import VisibilityOff from '@mui/icons-material/VisibilityOff'
import Link from '@mui/material/Link'

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} />
})

export default function NewPassword({code}) {
  const router = useRouter()
  const [showPassword, setShowPassword] = useState('')
  const [showPasswordConfirmation, setShowPasswordConfirmation] = useState('')
  const [password, setPassword] = useState('')
  const [passwordConfirmation, setPasswordConfirmation] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')
  const [open, setOpen] = useState(true)
  const [passwordSuccess, setPasswordSuccess] = useState(false)

  const resetForm = () => {
    setPassword('')
    setPasswordConfirmation('')
  }

  const changePassword = async () => {
    setLoading(true)
    try {
      await axios.post(`${API_URL}/auth/reset-password`, {
        code,
        password,
        passwordConfirmation
      })
      setLoading(false)
      setPasswordSuccess(true)
      setTimeout(() => {
        router.push('/soumet')
      }, 10_000)
    } catch {
      setOpen(true)
      setError('Une erreur s’est produite. Veuillez réessayer ultérieurement')
    }
  }

  const handleMouseDownPassword = event => {
    event.preventDefault()
  }

  const handleMouseDownPasswordConfirmation = event => {
    event.preventDefault()
  }

  const handleKeyUpPassword = event => {
    if (event.keyCode === 13) {
      handleClick()
    }
  }

  const handleKeyUpPasswordConfirmation = event => {
    if (event.keyCode === 13) {
      handleClick()
    }
  }

  const handleClick = async () => {
    if (password !== passwordConfirmation) {
      setOpen(true)
      setError('Les 2 mots de passe de correspondent pas')
      return
    }

    if (password.length < 6) {
      setOpen(true)
      setError('Le mot de passe est trop court, 6 caratères minimum')
      return
    }

    await changePassword()
    setLoading(false)
    resetForm()
  }

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

    setOpen(false)
    setError('')
  }

  return (
    <Container sx={{marginTop: 2}} maxWidth='sm'>
      <Box sx={{width: '100%'}}>
        <Typography sx={{textAlign: 'center'}} variant='h5' component='div'>Nouveau mot de passe</Typography>
        <FormControl fullWidth style={{marginTop: '1em'}}>
          <InputLabel htmlFor='password'>Mot de passe</InputLabel>
          <Input
            value={password}
            name='register-password'
            type={showPassword ? 'text' : 'password'}
            id='register-password'
            endAdornment={
              <InputAdornment position='end'>
                <IconButton
                  aria-label='password visibility'
                  size='large'
                  onClick={() => setShowPassword(!showPassword)}
                  onMouseDown={handleMouseDownPassword}
                >
                  {showPassword ? <Visibility /> : <VisibilityOff />}
                </IconButton>
              </InputAdornment>
            }
            onChange={event => setPassword(event.target.value)}
            onKeyUp={handleKeyUpPassword}
          />
        </FormControl>
        <FormControl fullWidth style={{marginTop: '1em'}}>
          <InputLabel htmlFor='password'>Vérification du mot de passe</InputLabel>
          <Input
            value={passwordConfirmation}
            name='verification-password'
            type={showPasswordConfirmation ? 'text' : 'password'}
            id='verification-password'
            error={password !== passwordConfirmation}
            endAdornment={
              <InputAdornment position='end'>
                <IconButton
                  aria-label='password visibility'
                  size='large'
                  onClick={() => setShowPasswordConfirmation(!showPassword)}
                  onMouseDown={handleMouseDownPasswordConfirmation}
                >
                  {showPasswordConfirmation ? <Visibility /> : <VisibilityOff />}
                </IconButton>
              </InputAdornment>
            }
            onChange={event => setPasswordConfirmation(event.target.value)}
            onKeyUp={handleKeyUpPasswordConfirmation}
          />
        </FormControl>
        <Button
          fullWidth
          style={{marginTop: 20}}
          variant='contained'
          color='primary'
          disabled={loading || password !== passwordConfirmation || password === ''}
          onClick={handleClick}
        >
          <Typography style={{fontWeight: 'bold'}}>
            Changer de mot de passe
          </Typography>
        </Button>
        <Button
          fullWidth
          style={{marginTop: 20}}
          variant='outlined'
          color='primary'
          onClick={() => router.push('/soumet')}
        >
          <Typography style={{fontWeight: 'bold'}}>
            Retour à la page de connexion
          </Typography>
        </Button>
      </Box>

      {loading && <LinearProgress size={24} style={{width: '100%', marginTop: '1em'}} />}

      {error && (
        <Snackbar
          open={open}
          autoHideDuration={6000}
          onClose={handleClose}
        >
          <Alert severity='error' onClose={handleClose}><strong>{error}</strong></Alert>
        </Snackbar>
      )}

      {passwordSuccess && (
        <Snackbar
          open={passwordSuccess}
          onClose={handleClose}
        >
          <Alert severity='info' onClose={handleClose}>Votre changement de mot de passe a été pris en compte. Vous serez redirigé vers la page de connexion. <Link underline='hover' color='inherit' href='/soumet'><strong>Cliquez ici si vous n’êtes pas redirigé vers la page de connexion</strong></Link></Alert>
        </Snackbar>
      )}
    </Container>
  )
}

NewPassword.propTypes = {
  code: PropTypes.string.isRequired
}
