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 { IoMdPersonAdd, IoMdReturnRight } from 'react-icons/io'
import { Link } from 'react-router-dom'
import { Box, Button, InputAdornment, Typography, Modal, TextField, Grid } from '@mui/material'
import { CgNotes } from 'react-icons/cg'
import { FaAngleDoubleUp, FaAngleDoubleDown, FaCog } from 'react-icons/fa'
import validateNOteSystem from './validation/NoteSystem'
import svgError from '../assets/error.svg'
import svgSuccess from '../assets/success.svg'
import { Tooltip } from 'react-tooltip'
import ModalFormMultiplicateur from './ModalFormMultiplicateur'

const SystemeNote = () => {
  const [formData, setFormData] = useState({
    id: '',
    admis: '',
    redouble: '',
    renvoyer: ''
  })

  
  const [noteSy, setNoteSy] = useState([])
  const [status, setStatus] = useState(200)
  
  /**
   * function to set the data in state
   * @param {*} e
   */
  const handleInputChange = (e) => {
    const { name, value } = e.target
    setFormData((prevData) => ({
      ...prevData,
      [name]: value
    }))
  }
  
  useEffect(() => {
    window.notesysteme.getSysteme().then((response) => {
      console.log('response:',response);
      setNoteSy(response)
    })
  }, [])
  
  useEffect(() => {
    if (noteSy) {
      setFormData({
        id: noteSy.id,
        admis: noteSy.admis || 0,
        redouble: noteSy.redouble || 0,
        renvoyer: noteSy.renvoyer || 0
      })
    }
  }, [noteSy])
  
  console.log(noteSy)
  
  const formSubmit = async (e) => {
    e.preventDefault()
    let valid = validateNOteSystem(admisRef.current, redoubleRef.current, renvoyerRef.current)
    
    if (valid) {
      let response = await window.notesysteme.updateNoteSysteme(formData)
      console.log(response)
      if (response.success) {
        setStatus(200)
        setOpen(true)
      }
    } else {
      setStatus(400)
      setOpen(true)
    }
  }
  console.log('form:',noteSy);
  
  const admisRef = useRef()
  const redoubleRef = useRef()
  const renvoyerRef = useRef()

  /**
   * 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={70} height={70} />{' '}
            <span>Modification des notes a été effectuée avec succès</span>
          </Typography>
        ) : (
          <Typography
            style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '10px' }}
          >
            <img src={svgError} alt="" width={70} height={70} />{' '}
            <span>Vérifiez les champs vides ou les séparateurs (doivent être un point)</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 [openForm, setOpenForm] = useState(false)

  const closeForm = () => {
    setOpenForm(false)
  }

  const openThisForm = () => {
    setOpenForm(true)
  }

  return (
    <div className={classe.mainHome}>
      <style>
        {`
        .custom-tooltips {
          font-size: 15px;
          border: solid 1px white !important;
          border-radius: 4px;
          text-transform: capitalize;
          font-weight: 600;
        }
      `}
      </style>
      {modals()}
      <ModalFormMultiplicateur open={openForm} onClose={closeForm} />
      <div className={classeAdd.header}>
        <div className={classe.h1style}>
          <div className={classeHome.blockTitle}>
            <h1 style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
              <CgNotes />
              Système d'organisation des notes
            </h1>
            <Link to={'#'} className="infocog" onClick={openThisForm}>
              <Button color="warning" variant="contained">
                <FaCog style={{ fontSize: '20px' }} />
              </Button>
            </Link>
            <Tooltip anchorSelect=".infocog" place="top" className="custom-tooltips">
              Changer le multiplicateur (credit * M)
            </Tooltip>
          </div>
        </div>
      </div>
      <div className={classeAdd.boxEtudiantsCard}>
        <Box
          sx={{
            position: 'absolute',
            top: '55%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            width: 1050,
            borderRadius: '2%',
            bgcolor: 'background.paper',
            boxShadow: 24,
            overflowY: 'auto',
            p: 4
          }}
          className="table-responsive"
        >
          <Box
            sx={{
              marginTop: '2%',
              display: 'flex',
              width: '100%',
              height: '40vh',
              gap: '20px',
              alignItems: 'start',
              justifyContent: 'center'
            }}
          >
            <form onSubmit={formSubmit}>
              <table className={'table table-bordered table-responsive'}>
                <thead className="bg-warning">
                  <tr style={{ fontWeight: 'bold' }}>
                    <td style={{ color: 'gray' }}>Status :</td>
                    <td style={{ color: 'gray' }}>Admis</td>
                    <td style={{ color: 'gray' }}>Autorisé à redoubler</td>
                    <td style={{ color: 'gray' }}>Remis à la famille</td>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <td style={{ color: 'gray', fontWeight: 'bold' }}>Notes :</td>
                    <td>
                      {/* <Grid container spacing={2}> */}
                      <Grid item xs={12} sm={3}>
                        <TextField
                          label={'Notes pour etre admis'}
                          name={'admis'}
                          color="warning"
                          fullWidth
                          placeholder="point séparateur"
                          className="inputToValidateExport"
                          value={formData.admis} // Access the correct value from formData
                          onChange={handleInputChange}
                          InputProps={{
                            startAdornment: (
                              <InputAdornment position="start">
                                <CgNotes />
                              </InputAdornment>
                            ),
                            endAdornment: (
                              <InputAdornment position="start">
                                <FaAngleDoubleUp className="text-success" />
                              </InputAdornment>
                            )
                          }}
                          inputRef={admisRef}
                          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> */}
                    </td>
                    <td>
                      {/* <Grid container spacing={2}> */}
                      <Grid item xs={12} sm={3}>
                        <TextField
                          label={'Notes pour autorisé à redoubler'}
                          name={'redouble'}
                          color="warning"
                          fullWidth
                          placeholder="point séparateur"
                          className="inputToValidateExport"
                          value={formData.redouble} // Access the correct value from formData
                          onChange={handleInputChange}
                          InputProps={{
                            startAdornment: (
                              <InputAdornment position="start">
                                <CgNotes />
                              </InputAdornment>
                            ),
                            endAdornment: (
                              <InputAdornment position="start">
                                <FaAngleDoubleDown className="text-danger" />
                              </InputAdornment>
                            )
                          }}
                          inputRef={redoubleRef}
                          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> */}
                    </td>
                    <td>
                      {/* <Grid container spacing={2}> */}
                      <Grid item xs={12} sm={3}>
                        <TextField
                          label={'Notes pour etre remis à la famille'}
                          name={'renvoyer'}
                          color="warning"
                          fullWidth
                          placeholder="point séparateur"
                          className="inputToValidateExport"
                          value={formData.renvoyer} // Access the correct value from formData
                          onChange={handleInputChange}
                          InputProps={{
                            startAdornment: (
                              <InputAdornment position="start">
                                <CgNotes />
                              </InputAdornment>
                            ),
                            endAdornment: (
                              <InputAdornment position="start">
                                <FaAngleDoubleDown className="text-danger" />
                              </InputAdornment>
                            )
                          }}
                          inputRef={renvoyerRef}
                          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> */}
                    </td>
                  </tr>
                </tbody>
              </table>
              <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 SystemeNote
