import React, { useEffect, useRef, useState } from 'react'
import classe from '../assets/AllStyleComponents.module.css'
import classeAdd from '../assets/AddNotes.module.css'
import classeHome from '../assets/Home.module.css'
import { Modal, Box, Typography, Button, InputAdornment, TextField, Grid } from '@mui/material'
import { CgNotes } from 'react-icons/cg'
import { IoMdReturnRight } from 'react-icons/io'
import { Link, useParams, useNavigate } from 'react-router-dom'
import svgSuccess from '../assets/success.svg'
import svgError from '../assets/error.svg'
import validateAddNote from './validation/AddNote'
import ModalUpdateParcoursEtudiant from './ModalUpdateParcoursEtudiant'

const AddNotes = () => {
  const { id, niveau, mention_id, parcours } = useParams()
  const [matieres, setMatieres] = useState([])
  const [formData, setFormData] = useState({}) // Initialize with an empty object
  const [etudiants, setEtudiants] = useState([])
  const navigate = useNavigate()
  const [openModal1, setOpenModal1] = useState(false)
  const oncloseModal1 = () => {
    setOpenModal1(false)
  }

  /**
   * Fetching the matieres
   */
  useEffect(() => {
    window.matieres.displayMatiereFromForm({ niveau, mention_id, parcours }).then((response) => {
      setMatieres(response)
    })

    window.etudiants.getSingle({ id }).then((response) => {
      setEtudiants(response)
    })

    if (parcours == 'Pas de parcours' && niveau != 'L1') {
      setOpenModal1(true)
    }
  }, [])

  const [isSubmitted, setIsSubmitted] = useState(false)
  const [parcoursChange, setParcourChanges] = useState('')
  const handleFormSubmit = (status, parcours) => {
    setIsSubmitted(status)
    setParcourChanges(parcours)
  }

  useEffect(() => {
    if (isSubmitted) {
      let parcours = parcoursChange

      window.matieres.displayMatiereFromForm({ niveau, mention_id, parcours }).then((response) => {
        setMatieres(response)
      })
      setIsSubmitted(false)
    }
  }, [isSubmitted])

  let niveauEtudiant = etudiants.niveau
  let AnneeScolaireEtudiant = etudiants.annee_scolaire

  /**
   * Update formData whenever matieres change
   */
  useEffect(() => {
    const initialFormData = matieres.reduce((acc, mat) => {
      acc[mat.id] = '' // Initialize each key with an empty string
      return acc
    }, {})
    setFormData(initialFormData)
  }, [matieres]) // Dependency array ensures this runs whenever `matieres` is updated

  const [disabled, setDisabled] = useState(false)

  /**
   * Handle form submission
   */
  const handleSubmit = async (e) => {
    e.preventDefault()
    const etudiant_id = id
    const etudiant_niveau = niveauEtudiant
    let valid = validateAddNote()
    let annee_scolaire = AnneeScolaireEtudiant
    let mention_id = etudiants.mention_id

    if (valid) {
      let response = await window.notes.insertNote({
        etudiant_id,
        etudiant_niveau,
        mention_id,
        formData,
        annee_scolaire
      })
      if (response.success) {
        setOpen(true)
        setStatut(200)
        setDisabled(true)
        const resetFormData = matieres.reduce((acc, mat) => {
          acc[mat.id] = '' // Reset each field to an empty string
          return acc
        }, {})
        setFormData(resetFormData)
      }
    } else {
      setOpen(true)
      setStatut(400)
    }
  }

  const [statut, setStatut] = useState(200)

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

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

  const handleClose2 = () => {
    navigate('/notes')
    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
        }}
      >
        {statut === 200 ? (
          <Typography
            style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '10px' }}
          >
            <img src={svgSuccess} alt="" width={70} height={70} />{' '}
            <span>
              Note de {etudiants.nom} {etudiants.prenom} en {etudiants.niveau} a été inserer avec
              succès
            </span>
          </Typography>
        ) : (
          <Typography
            style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '10px' }}
          >
            <img src={svgError} alt="" width={70} height={70} />{' '}
            <span>Inserer au moin un champ</span>
          </Typography>
        )}
        <Box
          sx={{
            marginTop: '2%',
            display: 'flex',
            gap: '20px',
            alignItems: 'end',
            justifyContent: 'flex-end'
          }}
        >
          {statut == 200 ? (
            <Button onClick={handleClose2} color="warning" variant="contained">
              OK
            </Button>
          ) : (
            <Button onClick={handleClose} color="warning" variant="contained">
              OK
            </Button>
          )}
        </Box>
      </Box>
    </Modal>
  )

  return (
    <div className={classe.mainHome}>
      {modals()}
      <ModalUpdateParcoursEtudiant
        onClose={oncloseModal1}
        open={openModal1}
        user_id={etudiants.id}
        onSubmit={handleFormSubmit}
      />
      <div className={classeAdd.header}>
        <div className={classe.h1style}>
          <div className={classeHome.blockTitle}>
            <h1 style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
              <CgNotes />
              Ajout note
            </h1>
            <Link to={'/student'}>
              <Button color="warning" variant="contained">
                <IoMdReturnRight style={{ fontSize: '20px' }} />
              </Button>
            </Link>
          </div>
        </div>

        {/* displaying */}
        <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', marginBottom: '3%' }}>
                  Ajout des notes :{' '}
                  <span style={{ color: '#ff9800' }}>
                    {etudiants.nom} {etudiants.prenom} en {etudiants.niveau}
                  </span>
                </h4>

                {/* map the all matiere to the form */}
                <Grid container spacing={2}>
                  {matieres.map((mat) => (
                    <Grid item xs={12} sm={3} key={mat.id}>
                      <TextField
                        label={mat.nom}
                        name={mat.id}
                        placeholder="point séparateur"
                        color="warning"
                        fullWidth
                        value={formData[mat.id] || ''} // Access the correct value from formData
                        onChange={(e) =>
                          setFormData({ ...formData, [mat.id]: e.target.value }) // Update the specific key
                        }
                        InputProps={{
                          startAdornment: (
                            <InputAdornment position="start">
                              <CgNotes />
                            </InputAdornment>
                          ),
                        }}
                        className="inputAddNote"
                        sx={{
                          '& .MuiOutlinedInput-root': {
                            '&:hover fieldset': {
                              borderColor: '#ff9800', // Set the border color on hover
                            },
                          },
                          '& .MuiInputBase-input::placeholder': {
                            fontSize: '11px', // Set the placeholder font size
                          },
                        }}
                      />
                    </Grid>
                  ))}
                </Grid>

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

export default AddNotes
