import React, { useEffect, 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, useParams } from 'react-router-dom'
import { Button, Grid, Paper, Modal, Typography, Box } from '@mui/material'
import { IoMdReturnRight } from 'react-icons/io'
import { FaPlus } from 'react-icons/fa'
import OutlinedInput from '@mui/material/OutlinedInput'
import InputLabel from '@mui/material/InputLabel'
import MenuItem from '@mui/material/MenuItem'
import FormControl from '@mui/material/FormControl'
import Select from '@mui/material/Select'
import svgSuccess from '../assets/success.svg'

const AssingMatiereToSemestre = () => {
  let { id } = useParams()

  const [mentions, setMentions] = useState([])
  const [matiereSemestre, setMatiereSemestre] = useState([])
  const [matiere, setMatiere] = useState({})
  const [semestre, setSemestre] = useState([])

  useEffect(() => {
    window.matieres.asignSemestre({ id }).then((response) => {
      setMentions(response)
    })

    window.matieres.getMatiereByID({ id }).then((response) => {
      setMatiere(response) // Set matiere
    })

    window.matieres.getSemestreMatiere({ id }).then((response) => {
      setMatiereSemestre(response) // Set matiere
    })

    window.matieres.getSemestre().then((response) => {
      setSemestre(response) // Set matiere
    })
  }, [id])

  // State to manage selected semestres for each mention
  const [selectedSemestres, setSelectedSemestres] = useState({})

  // Populate the initial state for selectedSemestres
  useEffect(() => {
    const initialSelectedSemestres = {}
    matiereSemestre.forEach((item) => {
      if (!initialSelectedSemestres[item.mention_id]) {
        initialSelectedSemestres[item.mention_id] = []
      }
      initialSelectedSemestres[item.mention_id].push(item.semestre_id)
    })
    setSelectedSemestres(initialSelectedSemestres)
  }, [matiereSemestre])

  // Handle change in Select
  const handleChange = (id) => (event) => {
    const {
      target: { value }
    } = event

    // Update state for the specific mention ID
    setSelectedSemestres((prevState) => ({
      ...prevState,
      [id]: typeof value === 'string' ? value.split(',') : value
    }))
  }

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

    let response = await window.matieres.insertUpdateMentionSemestre({ id, selectedSemestres })

    console.log(response)
    if (response.success) {
      setOpen(true)
    }
  }

  /**
   * 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
        }}
      >
        <Typography style={{ display: 'flex', alignItems: 'center', flexDirection: 'column' }}>
          <img src={svgSuccess} alt="" width={50} height={50} />{' '}
          <span>Changemet effectuée avec succès</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>
  )

  console.log(matiereSemestre)

  // Step 1: Preprocess matiereSemestre to create a mapping
  const preprocessSemestres = () => {
    const mapping = {}
    matiereSemestre.forEach((item) => {
      if (item.matiere_id === id) {
        // Filter by matiere_id if necessary
        if (!mapping[item.mention_id]) {
          mapping[item.mention_id] = []
        }
        mapping[item.mention_id].push(item.semestre_id)
      }
    })
    return mapping
  }

  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' }}>
              <FaPlus /> Asignation Semestre
            </h1>
            <Link to={'/matiere'}>
              <Button color="warning" variant="contained">
                <IoMdReturnRight style={{ fontSize: '20px' }} />
              </Button>
            </Link>
          </div>
        </div>
      </div>
      <Paper
        sx={{
          height: 'auto',
          minHeight: 500,
          display: 'flex',
          width: '100%'
        }}
      >
        <form style={{ width: '100%', padding: '2%' }} onSubmit={formSubmit}>
          <h5 style={{ textAlign: 'center', textDecoration: 'underline' }}>
            Choisissez les semestre dans la quelle on enseigne {matiere?.nom || 'la matière'}
          </h5>
          <Grid container spacing={2}>
            {mentions.map((mens) => (
              <Grid
                item
                xs={12}
                sm={4}
                sx={{
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                  padding: 5
                }}
                key={mens.id}
              >
                <div>
                  <div>
                    <b>
                      <i>{mens.nom}</i>
                    </b>
                  </div>
                  <div>
                    <FormControl sx={{ m: 1, width: 300 }}>
                      <InputLabel id={`semestre-label-${mens.id}`} color="warning">
                        Semestre
                      </InputLabel>
                      <Select
                        labelId={`semestre-label-${mens.id}`}
                        id={`semestre-select-${mens.id}`}
                        multiple
                        color="warning"
                        size="small"
                        required
                        value={selectedSemestres[mens.id] || []} // Pre-select semestres for this mention
                        onChange={handleChange(mens.id)} // Pass mention ID to handler
                        input={<OutlinedInput label="Semestre" />}
                        MenuProps={{
                          PaperProps: {
                            style: {
                              maxHeight: 200, // Limit dropdown height
                              width: 250 // Adjust dropdown width if needed
                            }
                          }
                        }}
                      >
                        {semestre.map((sem) => (
                          <MenuItem key={sem.id} value={sem.id}>
                            {sem.nom}
                          </MenuItem>
                        ))}
                      </Select>
                    </FormControl>
                  </div>
                </div>
              </Grid>
            ))}
          </Grid>
          <Grid
            item
            xs={12}
            style={{
              display: 'flex',
              gap: '30px',
              justifyContent: 'flex-end'
            }}
          >
            <Button type="submit" color="warning" variant="contained">
              Enregistrer
            </Button>
          </Grid>
        </form>
      </Paper>
    </div>
  )
}

export default AssingMatiereToSemestre
