import React, { useRef, useState } from 'react'
import {
  Modal,
  Box,
  Typography,
  Button,
  InputAdornment,
  TextField,
  Card,
  Grid,
  Container
} from '@mui/material'
import {
  FaUser,
  FaIdBadge,
  FaBirthdayCake,
  FaGraduationCap,
  FaCalendarAlt,
  FaFileUpload
} from 'react-icons/fa'

const ModalAddEtudiants = ({ open, handleClose }) => {
  /**
   * hook for storing data in the input
   */
  const [formData, setFormData] = useState({
    nom: '',
    prenom: '',
    photos: null,
    date_de_naissances: '',
    niveau: '',
    annee_scolaire: '',
    num_inscription: ''
  })

  /**
   * ref for each input
   */
  const nomRef = useRef()
  const prenomRef = useRef()
  const date_de_naissancesRef = useRef()
  const niveauRef = useRef()
  const annee_scolaireRef = useRef()
  const numero_inscriptionRef = useRef()
  const photosRef = useRef()

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

  const handleFileChange = (e) => {
    let img_file = e.target.files[0]
    const reader = new FileReader()
    reader.readAsDataURL(img_file)
    reader.onload = (ev) => {
      const url = ev.target.result
      // initialisation de nouvelle imageURL
      const image = document.createElement('img')
      image.src = url

      // create a new image
      image.onload = (event) => {
        let canvas = document.createElement('canvas')
        let ratio = 250 / event.target.width
        canvas.width = 250
        canvas.height = event.target.height * ratio
        const context = canvas.getContext('2d')
        context.drawImage(image, 0, 0, canvas.width, canvas.height)

        // new url
        const new_URL = canvas.toDataURL('image/jpeg', 90)
        // rendement de l'url a notre variable global
        setFormData((prevData) => ({
          ...prevData,
          photos: new_URL
        }))
      }
    }
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    // Handle form submission logic
    const response = await window.etudiants.insertEtudiant(formData)
    console.log(response)
  }

  return (
    <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: 600,
          bgcolor: 'background.paper',
          boxShadow: 24,
          p: 4
        }}
      >
        <Typography id="modal-title" variant="h6" component="h2">
          Ajoutez un etudiants
        </Typography>
        <Box
          sx={{
            marginTop: '2%',
            display: 'flex',
            gap: '20px',
            alignItems: 'end',
            justifyContent: 'flex-end'
          }}
        >
          <form onSubmit={handleSubmit}>
            <Grid container spacing={2}>
              {/* Nom and Prenom Fields */}
              <Grid item xs={12} sm={6}>
                <TextField
                  label="Nom"
                  name="nom"
                  color="secondary"
                  fullWidth
                  value={formData.nom}
                  onChange={handleInputChange}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <FaUser />
                      </InputAdornment>
                    )
                  }}
                  inputRef={nomRef}
                  sx={{
                    '& .MuiOutlinedInput-root': {
                      '&:hover fieldset': {
                        borderColor: 'rgb(156, 39, 176)' // Set the border color on hover
                      }
                    }
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <TextField
                  label="Prénom"
                  name="prenom"
                  fullWidth
                  color="secondary"
                  value={formData.prenom}
                  onChange={handleInputChange}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <FaUser />
                      </InputAdornment>
                    )
                  }}
                  inputRef={prenomRef}
                  sx={{
                    '& .MuiOutlinedInput-root': {
                      '&:hover fieldset': {
                        borderColor: 'rgb(156, 39, 176)' // Set the border color on hover
                      }
                    }
                  }}
                />
              </Grid>

              {/* Date de Naissance and Niveau Fields */}
              <Grid item xs={12} sm={6}>
                <TextField
                  label="Date de Naissance"
                  name="date_de_naissances"
                  fullWidth
                  color="secondary"
                  value={formData.date_de_naissances}
                  onChange={handleInputChange}
                  type="date"
                  InputLabelProps={{ shrink: true }}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <FaBirthdayCake />
                      </InputAdornment>
                    )
                  }}
                  inputRef={date_de_naissancesRef}
                  sx={{
                    '& .MuiOutlinedInput-root': {
                      '&:hover fieldset': {
                        borderColor: 'rgb(156, 39, 176)' // Set the border color on hover
                      }
                    }
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <TextField
                  label="Niveau"
                  name="niveau"
                  fullWidth
                  color="secondary"
                  value={formData.niveau}
                  onChange={handleInputChange}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <FaGraduationCap />
                      </InputAdornment>
                    )
                  }}
                  inputRef={niveauRef}
                  sx={{
                    '& .MuiOutlinedInput-root': {
                      '&:hover fieldset': {
                        borderColor: 'rgb(156, 39, 176)' // Set the border color on hover
                      }
                    }
                  }}
                />
              </Grid>

              {/* Année Univesitaire and Numéro d'Inscription Fields */}
              <Grid item xs={12} sm={6}>
                <TextField
                  label="Année Univesitaire"
                  name="annee_scolaire"
                  fullWidth
                  color="secondary"
                  value={formData.annee_scolaire}
                  onChange={handleInputChange}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <FaCalendarAlt />
                      </InputAdornment>
                    )
                  }}
                  inputRef={annee_scolaireRef}
                  sx={{
                    '& .MuiOutlinedInput-root': {
                      '&:hover fieldset': {
                        borderColor: 'rgb(156, 39, 176)' // Set the border color on hover
                      }
                    }
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <TextField
                  label="Numéro d'Inscription"
                  name="num_inscription"
                  fullWidth
                  color="secondary"
                  value={formData.num_inscription}
                  onChange={handleInputChange}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <FaIdBadge />
                      </InputAdornment>
                    )
                  }}
                  inputRef={numero_inscriptionRef}
                  sx={{
                    '& .MuiOutlinedInput-root': {
                      '&:hover fieldset': {
                        borderColor: 'rgb(156, 39, 176)' // Set the border color on hover
                      }
                    }
                  }}
                />
              </Grid>

              {/* Photos Field */}
              <Grid item xs={12}>
                <TextField
                  label="Photos"
                  name="photos"
                  fullWidth
                  color="secondary"
                  onChange={handleFileChange}
                  type="file"
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <FaFileUpload />
                      </InputAdornment>
                    )
                  }}
                  InputLabelProps={{
                    shrink: true
                  }}
                  inputRef={photosRef}
                  sx={{
                    '& .MuiOutlinedInput-root': {
                      '&:hover fieldset': {
                        borderColor: 'rgb(156, 39, 176)' // Set the border color on hover
                      }
                    }
                  }}
                />
              </Grid>

              {/* Submit Button */}
              <Grid
                item
                xs={12}
                style={{ display: 'flex', gap: '30px', justifyContent: 'flex-end' }}
              >
                <Button type="submit" color="secondary" variant="contained">
                  Enregister
                </Button>
                <Button
                  onClick={handleClose}
                  color="error"
                  variant="contained"
                  sx={{ width: '30px' }}
                >
                  Close
                </Button>
              </Grid>
            </Grid>
          </form>
        </Box>
      </Box>
    </Modal>
  )
}

export default ModalAddEtudiants
