import React, { useRef, useState } from 'react'
import classe from '../assets/Login.module.css'
import { FaEnvelope, FaLock, FaLockOpen } from 'react-icons/fa'
import { Link } from 'react-router-dom'
import {
  Modal,
  Box,
  Container,
  Grid,
  Card,
  Typography,
  TextField,
  Button,
  InputAdornment
} from '@mui/material'
import { validationForgotPassword } from './validation/ForgotPassword'

const ForgotPassword = () => {
  /**
   * hook to store data from the input field
   */
  const [email, setEmail] = useState()
  const [password, setPassword] = useState()
  const [passwordConfirmation, setPasswordConfirmation] = useState()

  /**
   * hook to open modal and set the sattus and message
   */
  const [open, setOpen] = useState(false)
  const [message, setMessage] = useState('')
  const [status, setStatus] = useState(null)

  const handleClose = () => setOpen(false)

  /**
   * ref for our email and password, confirm password input and the error span
   */
  const emailRef = useRef()
  const passwordRef = useRef()
  const passwordConfirmationRef = useRef()
  const emailError = useRef()
  const passwordError = useRef()
  const passwordConfirmationError = useRef()

  /**
   * function to return the view Modal
   *
   * @returns {JSX}
   */
  const modals = () => (
    <Modal
      open={open}
      onClose={handleClose}
      aria-labelledby="modal-title"
      aria-describedby="modal-description"
    >
      <Box
        sx={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          width: 400,
          bgcolor: 'background.paper',
          boxShadow: 24,
          p: 4
        }}
      >
        <Typography id="modal-title" variant="h6" component="h2">
          {status === 200 ? 'Success' : 'Error'}
        </Typography>
        <Typography id="modal-description" sx={{ mt: 2 }}>
          {message}
        </Typography>
        <Button onClick={handleClose}>Close</Button>
      </Box>
    </Modal>
  )

  /**
   * function to send the email verification
   * to change the password and redirect the user to login
   *
   * @param {any} e
   */
  const verification = async (e) => {
    e.preventDefault()

    let validation = validationForgotPassword(
      emailRef.current,
      passwordRef.current,
      passwordConfirmationRef.current,
      emailError.current,
      passwordError.current,
      passwordConfirmationError.current
    )
    console.log(validation)
    if (validation === true) {
      const response = await window.allUser.forgotPassword({
        email,
        password,
        passwordConfirmation
      })

      if (response.status === 200) {
        setMessage(response.message)
        setStatus(200)
      } else {
        setMessage(response.message)
        setStatus(response.status)
      }
      setOpen(true)
      console.log(response)
    }
  }

  return (
    <Container
      maxWidth={false}
      sx={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center' }}
      className={classe.container}
    >
      {modals()}
      <Grid container justifyContent="center">
        <Grid item xs={12} md={6} lg={4}>
          <Card className={`p-4 shadow ${classe.cards}`} sx={{ padding: 4, boxShadow: 3 }}>
            <Typography variant="h5" align="center" gutterBottom>
              Changer de mot de passe
            </Typography>
            <form onSubmit={verification} className={classe.formulaireLogin}>
              <TextField
                label="Email"
                variant="outlined"
                type="text"
                color="secondary"
                className={classe.input}
                fullWidth
                margin="normal"
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">
                      <FaEnvelope style={{ color: 'white' }} />
                    </InputAdornment>
                  )
                }}
                sx={{
                  '& .MuiOutlinedInput-root': {
                    '& fieldset': {
                      borderColor: 'white' // Set the border color when not focused
                    },
                    '&:hover fieldset': {
                      borderColor: 'rgb(156, 39, 176)' // Set the border color on hover
                    }
                  }
                }}
                placeholder="Entrer email"
                onChange={(e) => setEmail(e.target.value)}
                inputRef={emailRef}
              />
              <span ref={emailError} className="text-danger"></span>

              <TextField
                label="Nouveau Mot de passe"
                variant="outlined"
                type="password"
                className={classe.input}
                color="secondary"
                fullWidth
                margin="normal"
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">
                      <FaLock style={{ color: 'white' }} />
                    </InputAdornment>
                  )
                }}
                sx={{
                  '& .MuiOutlinedInput-root': {
                    '& fieldset': {
                      borderColor: 'white' // Set the border color when not focused
                    },
                    '&:hover fieldset': {
                      borderColor: 'rgb(156, 39, 176)' // Set the border color on hover
                    }
                  }
                }}
                placeholder="Mot de passe"
                onChange={(e) => setPassword(e.target.value)}
                inputRef={passwordRef}
              />
              <span ref={passwordError} className="text-danger"></span>

              <TextField
                label="Confirmation Mot de passe"
                variant="outlined"
                type="password"
                color="secondary"
                fullWidth
                margin="normal"
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">
                      <FaLockOpen style={{ color: 'white' }} />
                    </InputAdornment>
                  )
                }}
                sx={{
                  '& .MuiOutlinedInput-root': {
                    '& fieldset': {
                      borderColor: 'white' // Set the border color when not focused
                    },
                    '&:hover fieldset': {
                      borderColor: 'rgb(156, 39, 176)' // Set the border color on hover
                    }
                  }
                }}
                className={classe.input}
                placeholder="Confirmation Mot de passe"
                onChange={(e) => setPasswordConfirmation(e.target.value)}
                inputRef={passwordConfirmationRef}
              />
              <span ref={passwordConfirmationError} className="text-danger"></span>

              <Button
                variant="contained"
                color="secondary"
                type="submit"
                fullWidth
                sx={{ marginTop: 2 }}
              >
                Modifier
              </Button>

              <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '1rem' }}>
                <Link to="/login" style={{ color: '#FFFFFF' }}>
                  Se connecter
                </Link>
              </div>
            </form>
          </Card>
        </Grid>
      </Grid>
    </Container>
  )
}

export default ForgotPassword
