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

const SingleNotes = () => {
  let { id, niveau, scolaire } = useParams()
  const [notes, setNotes] = useState([])
  const [notesRepech, setNotesRepech] = useState([])
  const [formData, setFormData] = useState({})
  const [formData2, setFormData2] = useState({})
  const [etudiant, setEtudiant] = useState([])
  let annee_scolaire = scolaire
  const [screenRattrapage, setScreenRattrapage] = useState(false)

  useEffect(() => {
    window.etudiants.getSingle({ id }).then((response) => {
      setEtudiant(response)
    })
  }, [])

  useEffect(() => {
    let mention_id = etudiant.mention_id
    window.notes.getNotes({ id, niveau, mention_id }).then((response) => {
      setNotes(response)
    })

    window.noteRepech.getNotesRepech({ id, niveau, mention_id }).then((response) => {
      setNotesRepech(response)
    })
  }, [etudiant])

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

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

  const submitForm = async (e) => {
    e.preventDefault()
    let mention_id = etudiant.mention_id
    console.log('normal submited')
    let annee_scolaire = etudiant.annee_scolaire
    let response = await window.notes.updateNote({
      formData,
      niveau,
      id,
      mention_id,
      annee_scolaire
    })

    if (response.changes) {
      setMessage('Modification des notes terminer avec succès')
      setStatus(200)
      setOpen(true)
      window.noteRepech.getNotesRepech({ id, niveau, mention_id }).then((response) => {
        setNotesRepech(response)
      })

      window.notes.getNotes({ id, niveau, mention_id }).then((response) => {
        setNotes(response)
      })
    }
  }

  const submitForm2 = async (e) => {
    e.preventDefault()
    let mention_id = etudiant.mention_id
    console.log('rattrapage submited')
    let response = await window.noteRepech.updateNoteRepech({ formData2, niveau, id })

    console.log(response)
    if (response.changes) {
      setMessage('Modification des notes terminer avec succès')
      setStatus(200)
      setOpen(true)
      window.noteRepech.getNotesRepech({ id, niveau, mention_id }).then((response) => {
        setNotesRepech(response)
      })

      window.notes.getNotes({ id, niveau, mention_id }).then((response) => {
        setNotes(response)
      })
    }
  }

  const [status, setStatus] = useState(200)
  const [message, setMessage] = useState('')

  /**
   * 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
        }}
      >
        {status === 200 ? (
          <Typography
            style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '10px' }}
          >
            <img src={svgSuccess} alt="" width={50} height={50} /> <span>{message}</span>
          </Typography>
        ) : (
          <Typography
            style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '10px' }}
          >
            <img src={svgError} alt="" width={50} height={50} /> <span>{message}</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 nom = useRef()

  const changeScreen = () => {
    setScreenRattrapage(!screenRattrapage)
  }

  return (
    <div className={classe.mainHome}>
      {modals()}
      <div className={classeHome.header}>
        <div className={classe.h1style}>
          <div className={classeHome.blockTitle}>
            <h1>Mise a jour des notes</h1>
            <div style={{ display: 'flex', gap: '20px' }}>
              <Link onClick={() => window.history.back()}>
                <Button color="warning" variant="contained">
                  <IoMdReturnRight style={{ fontSize: '20px' }} />
                </Button>
              </Link>
            </div>
          </div>
        </div>
      </div>

      {/* displaying the form */}
      <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,
            overflowY: 'auto',
            p: 4
          }}
        >
          <Box
            sx={{
              marginTop: '2%',
              display: 'flex',
              width: '100%',
              height: '70vh',
              gap: '20px',
              alignItems: 'start',
              justifyContent: 'center'
            }}
          >
            {!screenRattrapage ? (
              <form action="" onSubmit={submitForm}>
                <h4 style={{ textAlign: 'center' }}>Mise a jour des notes</h4>
                {/* {/* map the all matiere and note to the form */}
                <Grid container spacing={2}>
                  {notes.map((note) => (
                    <Grid item xs={12} sm={3} key={note.nom}>
                      <TextField
                        label={note.nom}
                        name={note.matiere_id}
                        color="warning"
                        fullWidth
                        placeholder="point séparateur"
                        className="inputToValidateExport"
                        value={formData[note.matiere_id] || ''} // Access the correct value from formData
                        onChange={
                          (e) => setFormData({ ...formData, [note.id]: e.target.value }) // Update the specific key
                        }
                        InputProps={{
                          startAdornment: (
                            <InputAdornment position="start">
                              <CgNotes />
                            </InputAdornment>
                          )
                        }}
                        inputRef={nom}
                        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: '2%'
                  }}
                >
                  <Button type="button" color="warning" variant="contained" onClick={changeScreen}>
                    Voir les notes de rattrapage
                  </Button>
                  <Button type="submit" color="warning" variant="contained">
                    Enregister
                  </Button>
                </Grid>
              </form>
            ) : (
              <form action="" onSubmit={submitForm2}>
                <h4 style={{ textAlign: 'center' }}>Mise a jour des notes de Rattrapage</h4>
                {/* {/* map the all matiere and note to the form */}
                <Grid container spacing={2}>
                  {notesRepech.length === 0 ? (
                    // Show this message if notesRepech is empty
                    <Grid item xs={12}>
                      <h4 style={{ textAlign: 'center', color: 'green' }}>
                        L'étudiant a validé tous les crédits.
                      </h4>
                    </Grid>
                  ) : (
                    // Render form fields if notesRepech contains data
                    notesRepech.map((note) => (
                      <Grid item xs={12} sm={4} key={note.nom}>
                        <TextField
                          label={note.nom}
                          name={note.matiere_id}
                          color="warning"
                          fullWidth
                          placeholder="point séparateur"
                          className="inputToValidateExport"
                          value={formData2[note.matiere_id] || ''} // Access the correct value from formData2
                          onChange={
                            (e) => setFormData2({ ...formData2, [note.id]: e.target.value }) // Update the specific key
                          }
                          InputProps={{
                            startAdornment: (
                              <InputAdornment position="start">
                                <CgNotes />
                              </InputAdornment>
                            )
                          }}
                          inputRef={nom}
                          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: '2%'
                  }}
                >
                  <Button type="button" color="warning" variant="contained" onClick={changeScreen}>
                    Voir les notes session normale
                  </Button>
                  <Button type="submit" color="warning" variant="contained">
                    Enregister
                  </Button>
                </Grid>
              </form>
            )}
          </Box>
        </Box>
      </div>
    </div>
  )
}

export default SingleNotes
