import React, { useEffect, useRef, useState } from 'react'
import classe from '../assets/AllStyleComponents.module.css'
import classeAdd from '../assets/AddStudent.module.css'
import { Link, useNavigate } from 'react-router-dom'
import { IoMdPersonAdd, IoMdReturnRight } from 'react-icons/io'
import { FaFileExcel, FaUser } from 'react-icons/fa'
import { Box, Button, InputAdornment, TextField, Grid, Modal, Typography } from '@mui/material'
import classeHome from '../assets/Home.module.css'
import validationNote from './validation/AddNiveau'
import svgSuccess from '../assets/success.svg'

const AddNiveau = () => {
  const navigate = useNavigate()
  /**
   * hook for storing data in the input
   */
  const [formData, setFormData] = useState({
    nom: ''
  })
  const [niveau, setNiveau] = useState([])
  /**
   * hook to open modal
   */
  const [open, setOpen] = useState(false)

  /**
   * function to close modal
   */
  const handleClose = () => {
    setOpen(false)
    navigate('/niveau')
  }

  useEffect(() => {
    window.niveaus.getNiveau().then((response) => {
      setNiveau(response)
    })
  }, [])

  /**
   * function to set the data in state
   * @param {*} e
   */
  const handleInputChange = (e) => {
    const { name, value } = e.target
    setFormData((prevData) => ({
      ...prevData,
      [name]: value
    }))
  }

  const nomRef = useRef()
  const nomError = 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: 450,
          bgcolor: 'background.paper',
          boxShadow: 24,
          p: 4
        }}
      >
        <Typography style={{ display: 'flex', alignItems: 'center', flexDirection: 'column' }}>
          <img src={svgSuccess} alt="" width={50} height={50} />{' '}
          <span>Insertion a été effectuée avec succès</span>
        </Typography>
        <Box
          sx={{
            marginTop: '2%',
            display: 'flex',
            gap: '20px',
            alignItems: 'end',
            justifyContent: 'flex-end'
          }}
        >
          <Button onClick={handleClose} color="warning" variant="contained">
            OK
          </Button>
        </Box>
      </Box>
    </Modal>
  )

  const formSubmit = async (e) => {
    e.preventDefault()
    let niveauNom = []
    niveau.map((niv) => {
      niveauNom.push(niv.nom)
    })
    let validation = validationNote(nomRef.current, nomError.current, niveauNom)

    if (validation) {
      let response = await window.niveaus.insertNiveau(formData)

      let responses = JSON.parse(response)
      if (responses.changes == 1) {
        setOpen(true)
        setFormData({
          nom: ''
        })
      }
    }
  }

  return (
    <div className={classe.mainHome}>
      {modals()}
      <div className={classeAdd.header}>
        <div className={classe.h1style}>
          <div className={classeHome.blockTitle}>
            <h1 style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
              <IoMdPersonAdd />
              Ajout niveau
            </h1>
            <Link to={'/niveau'}>
              <Button color="warning" variant="contained">
                <IoMdReturnRight style={{ fontSize: '20px' }} />
              </Button>
            </Link>
          </div>
        </div>
      </div>

      <div className={classeAdd.boxEtudiantsCard}>
        <Box
          sx={{
            position: 'absolute',
            top: '50%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            width: 700,
            borderRadius: '2%',
            bgcolor: 'background.paper',
            boxShadow: 24,
            p: 4
          }}
        >
          <h3 style={{ textAlign: 'center', paddingBottom: '15px', textDecoration: 'underline' }}>
            Ajout d'un niveau
          </h3>
          <div style={{ textAlign: 'right', fontWeight: 'bold' }}>
            <Link to={'/importniveau'} style={{ textDecoration: 'none', color: 'orange' }}>
              Importer un fichier excel <FaFileExcel />
            </Link>
          </div>
          <Box
            sx={{
              marginTop: '2%',
              width: '100%'
            }}
          >
            <form onSubmit={formSubmit}>
              <TextField
                label="Nom"
                name="nom"
                color="warning"
                fullWidth
                placeholder="L1 ou L2 ou L3 ou M1 ou M2 ou D1 ou D2 ou D3"
                value={formData.nom}
                onChange={handleInputChange}
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">
                      <FaUser />
                    </InputAdornment>
                  )
                }}
                inputRef={nomRef}
                sx={{
                  marginBottom: '5px',
                  '& .MuiOutlinedInput-root': {
                    '&:hover fieldset': {
                      borderColor: '#ff9800' // Set the border color on hover
                    }
                  }
                }}
              />
              <span style={{ color: 'red', marginBottom: '15px' }} ref={nomError}></span>
              <br />
              {/* Submit Button */}
              <Grid
                item
                xs={12}
                style={{ display: 'flex', gap: '30px', justifyContent: 'flex-end' }}
              >
                <Button type="submit" color="warning" variant="contained">
                  Enregister
                </Button>
              </Grid>
            </form>
          </Box>
        </Box>
      </div>
    </div>
  )
}

export default AddNiveau
