import React, { useEffect, useRef, useState } from 'react'
import classe from '../assets/AllStyleComponents.module.css'
import classeAdd from '../assets/AddStudent.module.css'
import classeHome from '../assets/Home.module.css'
import { FaPenToSquare } from 'react-icons/fa6'
import { IoMdReturnRight } from 'react-icons/io'
import { Link, useParams } from 'react-router-dom'
import { Box, Button, InputAdornment, Typography, Modal, TextField, Grid } from '@mui/material'
import validationSingleNiveau from './validation/SingleNiveau'
import svgSuccess from '../assets/success.svg'

const SingleNiveau = () => {
  const { id } = useParams()

  const [niveau, setNiveau] = useState([])
  const [allNiveau, setAllNiveau] = useState([])

  useEffect(() => {
    window.niveaus.getSingleNiveau({ id }).then((response) => {
      setNiveau(response)
    })

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

  useEffect(() => {
    if (niveau) {
      setFormData({
        nom: niveau.nom || '',
        id: niveau.id || id
      })
    }
  }, [niveau])

  const [formData, setFormData] = useState({
    nom: '',
    id: id
  })

  const handleChange = (e) => {
    const { name, value } = e.target
    setFormData({
      ...formData,
      [name]: value
    })
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    let niveauNom = []
    allNiveau.map((niv) => {
      niveauNom.push(niv.nom)
    })
    // let validation = validationSingleNiveau(nomRef.current, errorRef.current, niveauNom)

    // if (validation) {
    let response = await window.niveaus.updateSingleNiveau(formData)
    console.log(response)

    if (response.success) {
      setOpen(true)
    }

    if (!response.success) {
      errorRef.current.textContent = `${formData.nom} existe déjà`
    }
    // }
  }

  /**
   * hook to open modal
   */
  const [open, setOpen] = useState(false)

  /**
   * function to close modal
   */
  const handleClose = () => setOpen(false)

  /**
   * 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', flexDirection: 'column', alignItems: 'center', gap: '10px' }}
        >
          <img src={svgSuccess} alt="" width={70} height={70} />{' '}
          <span>Modification 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 nomRef = useRef()
  const errorRef = useRef()

  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' }}>
              <FaPenToSquare />
              Mise à jour niveau
            </h1>
            <Link to={'/niveau'}>
              <Button color="warning" variant="contained">
                <IoMdReturnRight style={{ fontSize: '20px' }} />
              </Button>
            </Link>
          </div>
        </div>
      </div>

      <div className={classeHome.boxEtudiantsCard}>
        <Box
          sx={{
            position: 'absolute',
            top: '55%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            width: 700,
            borderRadius: '2%',
            bgcolor: 'background.paper',
            boxShadow: 24,
            p: 4
          }}
        >
          <Box
            sx={{
              marginTop: '2%',
              display: 'flex',
              width: '100%',
              gap: '20px',
              alignItems: 'start',
              justifyContent: 'center'
            }}
          >
            <form onSubmit={handleSubmit} style={{ width: '100%' }}>
              <h4 style={{ textAlign: 'center' }}>modification niveau</h4>
              <Grid container spacing={2}>
                {/* Nom Fields */}
                <Grid item xs={12} sm={12}>
                  <TextField
                    label="Nom"
                    name="nom"
                    color="warning"
                    fullWidth
                    value={formData.nom}
                    onChange={handleChange}
                    InputProps={{
                      startAdornment: (
                        <InputAdornment position="start">{/* <FaUser /> */}</InputAdornment>
                      )
                    }}
                    inputRef={nomRef}
                    sx={{
                      '& .MuiOutlinedInput-root': {
                        '&:hover fieldset': {
                          borderColor: '#ff9800' // Set the border color on hover
                        }
                      }
                    }}
                  />
                  <span className="text-danger" ref={errorRef}></span>
                </Grid>

                {/* Submit Button */}
                <Grid
                  item
                  xs={12}
                  style={{ display: 'flex', gap: '30px', justifyContent: 'flex-end' }}
                >
                  <Button type="submit" color="warning" variant="contained">
                    Enregister
                  </Button>
                </Grid>
              </Grid>
            </form>
          </Box>
        </Box>
      </div>
    </div>
  )
}

export default SingleNiveau
