import { useEffect, 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, useParams } from 'react-router-dom'
import { IoMdReturnRight } from 'react-icons/io'
import { Modal, Box, Typography, Button, InputAdornment, TextField, Grid } from '@mui/material'
import { FaCalendarAlt } from 'react-icons/fa'
import svgError from '../assets/error.svg'
import svgSuccess from '../assets/success.svg'
import { BsCalendar2Date } from 'react-icons/bs'
import dayjs from 'dayjs'

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

  const [scolaire, setScolaire] = useState([])
  const [status, setStatus] = useState(200)
  const [open, setOpen] = useState(false)

  useEffect(() => {
    window.anneescolaire.getSingleAnneeScolaire({ id }).then((response) => {
      setScolaire(response)
    })
  }, [])

  useEffect(() => {
    setFormData((prev) => ({
      ...prev,
      code: scolaire.code,
      debut: dayjs(scolaire.debut).format('YYYY-MM-DD'),
      fin: dayjs(scolaire.fin).format('YYYY-MM-DD'),
      id: scolaire.id
    }))
  }, [scolaire])

  /**
   * 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 response = await window.anneescolaire.updateAnneeScolaire(formData)

    if (response.success) {
      setOpen(true)
      setStatus(200)
    } else {
      setStatus(400)
      setOpen(true)
    }
  }

  const handleClose = () => setOpen(false)

  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
          sx={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            gap: 2
          }}
        >
          <img src={status === 200 ? svgSuccess : svgError} alt="" width={70} height={70} />
          <span> {status === 200 ? 'Mise à jour effectuée avec succès' : 'Erreur'}</span>
        </Typography>
        <Box
          sx={{
            marginTop: 2,
            display: 'flex',
            justifyContent: 'flex-end'
          }}
        >
          <Button onClick={handleClose} 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' }}>
              <BsCalendar2Date />
              Mise a jour 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
            style={{
              width: '50%',
              padding: '1%',
              height: '20%',
              border: 'solid 2px orange',
              borderRadius: '10px'
            }}
            onSubmit={formSubmit}
          >
            <h4 style={{ textAlign: 'center', padding: '0 0 3% 0' }}>
              mise a jour 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}
                  required
                  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}
                  required
                  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}
                  required
                  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 SingleAnneeScolaire
