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 { Link, useNavigate } from 'react-router-dom'
import { IoMdReturnRight } from 'react-icons/io'
import {
  Box,
  Button,
  InputAdornment,
  Typography,
  Modal,
  TextField,
  Grid,
  Autocomplete
} from '@mui/material'
import { BsBookmarkPlusFill } from 'react-icons/bs'
import { FaBook, FaClipboardList, FaClock, FaFileExcel } from 'react-icons/fa'
import validationMatiereAdd from './validation/ValidationMatiereAdd'
import svgSuccess from '../assets/success.svg'
import ChangeCapitalize from './function/ChangeCapitalizeLetter'
import { MdOutlineNumbers } from 'react-icons/md'
import { IoBookmark } from 'react-icons/io5'
import ChangeCapital from './function/ChangeCapitalLetter'
import { CgPathUnite } from 'react-icons/cg'

const AddMatiere = () => {
  const [formData, setFormData] = useState({
    nom: '',
    credit: '',
    uniter: '',
    ue: ''
  })

  const navigate = useNavigate()

  const [matieres, setMatieres] = useState([])
  const [mention, setMention] = useState([])

  useEffect(() => {
    window.matieres.getMatiere().then((response) => {
      setMatieres(response)
    })

    window.mention.getMention().then((response) => {
      setMention(Array.isArray(response) ? response : [])
    })
  }, [])

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

  /**
   * function to close modal
   */
  const handleClose = () => {
    setOpen(false)
    navigate('/matiere')
  }

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

  const nomRef = useRef()
  const errorRef = useRef()
  const creditRef = useRef()
  const ueRef = useRef()
  const uniterRef = useRef()

  const formSubmit = async (e) => {
    e.preventDefault()

    let arrayMatiere = []

    matieres.map((matiere) => {
      arrayMatiere.push(matiere.nom)
    })

    let valid = validationMatiereAdd(
      nomRef.current,
      errorRef.current,
      arrayMatiere,
      creditRef.current
    )
    console.log(formData, valid)
    if (valid) {
      let response = await window.matieres.createMatiere(formData)
      console.log(response)
      if (response.success) {
        setOpen(true)
      }

      if (response.code) {
        errorRef.current.textContent = `${formData.nom} existe déjà`
      }
    }
  }

  /**
   * 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
        }}
      >
        <Typography style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
          <img src={svgSuccess} alt="" width={50} height={50} />{' '}
          <span>Matière insérer avec succes</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>
  )

  return (
    <div className={classe.mainHome}>
      {modals()}
      <div className={classeAdd.header}>
        <div className={classe.h1style}>
          <div className={classeHome.blockTitle}>
            <h1 style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
              <BsBookmarkPlusFill />
              Ajout Matière
            </h1>
            <Link to={'/matiere'}>
              <Button color="warning" variant="contained">
                <IoMdReturnRight style={{ fontSize: '20px' }} />
              </Button>
            </Link>
          </div>
        </div>
      </div>

      {/* displaying the formulaire */}
      <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,
            p: 4
          }}
        >
          <div style={{ textAlign: 'right', fontWeight: 'bold' }}>
            <Link to={'/addmatiere/import'} style={{ textDecoration: 'none', color: 'orange' }}>
              Importer un fichier excel <FaFileExcel />
            </Link>
          </div>
          <h3 style={{ textAlign: 'center', paddingBottom: '15px', textDecoration: 'underline' }}>
            Ajout d'un Matière
          </h3>
          <Box
            sx={{
              marginTop: '2%',
              width: '100%'
            }}
          >
            <form onSubmit={formSubmit}>
              <Grid container spacing={2}>
                <Grid item xs={12} sm={6}>
                  <TextField
                    label="Nom"
                    name="nom"
                    color="warning"
                    fullWidth
                    placeholder="Nom du matière"
                    value={formData.nom}
                    onChange={handleInputChange}
                    onInput={() => ChangeCapitalize(nomRef)}
                    InputProps={{
                      startAdornment: (
                        <InputAdornment position="start">
                          <FaBook />
                        </InputAdornment>
                      )
                    }}
                    inputRef={nomRef}
                    sx={{
                      marginBottom: '5px',
                      '& .MuiOutlinedInput-root': {
                        '&:hover fieldset': {
                          borderColor: '#ff9800' // Set the border color on hover
                        }
                      }
                    }}
                  />
                </Grid>
                <Grid item xs={12} sm={6}>
                  <TextField
                    label="Crédit"
                    name="credit"
                    color="warning"
                    fullWidth
                    placeholder="Crédit pour la matiere"
                    type="number"
                    value={formData.credit}
                    onChange={handleInputChange}
                    InputProps={{
                      startAdornment: (
                        <InputAdornment position="start">
                          <MdOutlineNumbers />
                        </InputAdornment>
                      )
                    }}
                    inputProps={{ min: 1 }}
                    inputRef={creditRef}
                    sx={{
                      marginBottom: '5px',
                      '& .MuiOutlinedInput-root': {
                        '&:hover fieldset': {
                          borderColor: '#ff9800' // Set the border color on hover
                        }
                      }
                    }}
                  />
                </Grid>
                {/* <Grid item xs={12} sm={6}>
              <TextField
                label="Semestre"
                name="semestre"
                color='warning'
                fullWidth
                placeholder='exemple S1, S2, S3, S4'
                type='text'
                value={formData.semestre}
                onChange={handleInputChange}
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">
                      <CiCalendar />
                    </InputAdornment>
                  ),
                }}
                inputProps={{ min: 1 }}
                inputRef={semestreRef}
                sx={{
                  marginBottom:"5px",
                  '& .MuiOutlinedInput-root': {
                    '&:hover fieldset': {
                      borderColor: '#ff9800', // Set the border color on hover
                    },
                  },
                }}
              />
            </Grid> */}
                <Grid item xs={12} sm={6}>
                  <TextField
                    label="Unité d'enseignement"
                    name="uniter"
                    color="warning"
                    fullWidth
                    placeholder="Le matiere sera dans quelle unité d'enseignement"
                    value={formData.uniter}
                    onChange={handleInputChange}
                    onInput={() => ChangeCapital(uniterRef)}
                    InputProps={{
                      startAdornment: (
                        <InputAdornment position="start">
                          <IoBookmark />
                        </InputAdornment>
                      )
                    }}
                    inputProps={{ min: 1 }}
                    inputRef={uniterRef}
                    sx={{
                      marginBottom: '5px',
                      '& .MuiOutlinedInput-root': {
                        '&:hover fieldset': {
                          borderColor: '#ff9800' // Set the border color on hover
                        }
                      }
                    }}
                  />
                </Grid>
                <Grid item xs={12} sm={6}>
                  <TextField
                    label="UE"
                    name="ue"
                    color="warning"
                    fullWidth
                    placeholder="TI2"
                    value={formData.ue}
                    onInput={() => ChangeCapital(ueRef)}
                    onChange={handleInputChange}
                    type="text"
                    InputProps={{
                      startAdornment: (
                        <InputAdornment position="start">
                          <CgPathUnite />
                        </InputAdornment>
                      )
                    }}
                    inputProps={{ min: 1 }}
                    inputRef={ueRef}
                    sx={{
                      marginBottom: '5px',
                      '& .MuiOutlinedInput-root': {
                        '&:hover fieldset': {
                          borderColor: '#ff9800' // Set the border color on hover
                        }
                      }
                    }}
                  />
                </Grid>
                {/* <Grid item xs={12} sm={6}>
            <Autocomplete
              multiple
              options={mention} // Options array for Autocomplete
              getOptionLabel={(option) => option.nom || ""} // Safely access `nom`
              value={formData.mention_id.map(id => mention.find(item => item.id === id)) || []} // Bind selected values to form data
              onChange={(event, newValue) => {
                setFormData((prevData) => ({
                  ...prevData,
                  mention_id: newValue.map((item) => item.id), // Store only the IDs of selected mentions
                }));
              }}
              isOptionEqualToValue={(option, value) => option.id === value.id} // Ensure correct matching of options
              renderInput={(params) => (
                <TextField
                  {...params}
                  label="Mention"
                  color="warning"
                  placeholder="Sélectionnez les mentions"
                  InputProps={{
                    ...params.InputProps,
                    startAdornment: (
                      <>
                        <InputAdornment position="start">
                          <FaClipboardList />
                        </InputAdornment>
                        {params.InputProps.startAdornment}
                      </>
                    ),
                  }}
                  sx={{
                    marginBottom: "5px",
                    '& .MuiOutlinedInput-root': {
                      '&:hover fieldset': {
                        borderColor: '#ff9800', // Set border color on hover
                      },
                    },
                  }}
                />
              )}
            />

            </Grid> */}
              </Grid>
              <span style={{ color: 'red', marginBottom: '15px' }} ref={errorRef}></span>
              <br />
              <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 AddMatiere
