import React, { useRef, useState } from 'react'
import classe from '../assets/AllStyleComponents.module.css'
import classeHome from '../assets/Home.module.css'
import Paper from '@mui/material/Paper'
import { Link, useNavigate } from 'react-router-dom'
import { IoMdReturnRight } from 'react-icons/io'
import { Modal, Box, Typography, Button, InputAdornment, TextField, Grid } from '@mui/material'
import { FaCalendarAlt, FaCalendarPlus } from 'react-icons/fa'
import validationAnneeScolaire from './validation/ValidationAddAnneeScolaire'
import svgError from '../assets/error.svg'
import svgSuccess from '../assets/success.svg'

const AddAnneeScolaire = () => {
  const [formData, setFormData] = useState({
    code: '',
    debut: '',
    fin: ''
  })

  const debutRef = useRef()
  const codeRef = useRef()
  const finRef = useRef()

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

  const formSubmit = async (e) => {
    e.preventDefault()
    let isValid = validationAnneeScolaire(codeRef.current, debutRef.current, finRef.current)

    if (isValid) {
      let response = await window.anneescolaire.createAnneeScolaire(formData)
      console.log(response)
      if (response.success) {
        setStatus(200)
        setOpen(true)
      } else {
        setStatus(400)
        setOpen(true)
      }
    } else {
      setStatus(400)
      setOpen(true)
    }
  }

  const [status, setStatus] = useState(200)

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

  /**
   * function to close modal
   */
  const handleClose = () => {
    setOpen(false)
    window.history.back()
  }
  const handleClose2 = () => {
    setOpen(false)
  }

  /**
   * function to return the view Modal
   *
   * @returns {JSX}
   */
  const modals = () => (
    <Modal
      open={open}
      onClose={status === 200 ? handleClose : 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' }}>
            <img src={svgSuccess} alt="" width={50} height={50} />{' '}
            <span>Année Univesitaire insérer avec succes</span>
          </Typography>
        ) : (
          <Typography style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            <img src={svgError} alt="" width={50} height={50} />{' '}
            <span>Erreur, veuillez réessayer</span>
          </Typography>
        )}
        <Box
          sx={{
            marginTop: '2%',
            display: 'flex',
            gap: '20px',
            alignItems: 'end',
            justifyContent: 'flex-end'
          }}
        >
          {status === 200 ? (
            <Button onClick={handleClose} color="warning" variant="contained">
              OK
            </Button>
          ) : (
            <Button onClick={handleClose2} color="warning" variant="contained">
              OK
            </Button>
          )}
        </Box>
      </Box>
    </Modal>
  )

  return (
    <div className={classe.mainHome}>
      {modals()}
      <div className={classeHome.header}>
        <div className={classe.h1style}>
          <div className={classeHome.blockTitle}>
            <h1 style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
              <FaCalendarPlus /> Ajout Année Univesitaire
            </h1>
            <Link to={'#'} onClick={() => window.history.back()}>
              <Button color="warning" variant="contained">
                <IoMdReturnRight style={{ fontSize: '20px' }} />
              </Button>
            </Link>
          </div>
        </div>
      </div>

      <div className={classeHome.boxEtudiantsCard}>
        <Paper
          sx={{
            width: '100%',
            height: '100%', // Auto height to make the grid responsive
            minHeight: 500, // Ensures a minimum height
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            justifyContent: 'center'
          }}
        >
          <form
            onSubmit={formSubmit}
            style={{
              width: '50%',
              padding: '1%',
              height: '20%',
              border: 'solid 2px orange',
              borderRadius: '10px'
            }}
          >
            <h4 style={{ textAlign: 'center', padding: '0 0 3% 0' }}>
              Creation de nouvelle Année Univesitaire
            </h4>
            <Grid container spacing={2}>
              <Grid item xs={12} sm={6}>
                <TextField
                  label={'Année Univesitaire'}
                  name={'code'}
                  placeholder="2024-2025"
                  color="warning"
                  fullWidth
                  value={formData.code}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <FaCalendarAlt />
                      </InputAdornment>
                    )
                  }}
                  onChange={handleInputChange}
                  inputRef={codeRef}
                  className="inputAddNote"
                  sx={{
                    '& .MuiOutlinedInput-root': {
                      '&:hover fieldset': {
                        borderColor: '#ff9800' // Set the border color on hover
                      }
                    },
                    '& .MuiInputBase-input::placeholder': {
                      fontSize: '14px' // Set the placeholder font size
                    }
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <TextField
                  label={'Date de début'}
                  name={'debut'}
                  color="warning"
                  onChange={handleInputChange}
                  inputRef={debutRef}
                  value={formData.debut}
                  fullWidth
                  type="date"
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <FaCalendarAlt />
                      </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 item xs={12} sm={6}>
                <TextField
                  label={'Date de fin'}
                  name={'fin'}
                  color="warning"
                  fullWidth
                  type="date"
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <FaCalendarAlt />
                      </InputAdornment>
                    )
                  }}
                  onChange={handleInputChange}
                  inputRef={finRef}
                  value={formData.fin}
                  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
                item
                xs={12}
                style={{ display: 'flex', gap: '30px', justifyContent: 'flex-end' }}
              >
                <Button type="submit" color="warning" variant="contained">
                  Enregister
                </Button>
              </Grid>
            </Grid>
          </form>
        </Paper>
      </div>
    </div>
  )
}

export default AddAnneeScolaire
