import React, { useEffect, useState } from 'react';
import {
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  Button,
  Box,
  Grid,
  FormControl,
  InputLabel,
  Select,
  OutlinedInput,
  MenuItem
} from '@mui/material'

const NiveauMatiere = ({ open, onClose, matiere_id }) => {
  const [formData, setFormData] = useState({
    niveau_id: '',
    id: ''
  })

  const [niveaux, setNiveaux] = useState([])
  const [niveauxMatiere, setNiveauxMatiere] = useState([])
  console.log(niveaux);

  useEffect(() => {
    window.niveaus.getNiveau().then((response) => {
      setNiveaux(response)
    })
  }, [])


  useEffect(() => {
    if (niveauxMatiere.length !== 0) {
      const niveauIds = niveauxMatiere.map((item) => item.niveau_id)

      setFormData((prevState) => ({
        ...prevState,
        niveau_id: niveauIds
      }))
    }
  }, [niveauxMatiere])

  useEffect(() => {
    if (matiere_id) {
      setFormData(prev => ({
        ...prev,
        id: matiere_id
      }));
    }
  }, [matiere_id]);
  
  

  const handleChange = (event) => {
    const { name, value } = event.target

    setFormData(prevState => ({
      ...prevState,
      niveau_id: value // pas de tableau
    }));
    
  }

  const formSubmit = async (e) => {
    e.preventDefault();
    console.log("Form envoyé côté front:", formData);
    let response = await window.matieres.updateMatiereNiveau(formData);
    console.log("Réponse backend:", response);
    if (response.success) {
      onClose();
    }
  };
   

  return (
    <Dialog open={open} onClose={onClose}>
      <form action="" onSubmit={formSubmit}>
        <DialogTitle>Assignation à des niveaux</DialogTitle>
        <DialogContent>
          <Box sx={{ flexGrow: 1 }}>
            <Grid container spacing={2}>
              <Grid item xs={12} sm={6}>
                <FormControl sx={{ m: 1, width: 300 }}>
                  <InputLabel id="niveaux-select-label" color="warning">
                    Niveaux
                  </InputLabel>
                  <Select
                    labelId="niveaux-select-label"
                    id="niveaux-select"
                    name="niveau_id"
                    value={formData.niveau_id || ''}
                    onChange={handleChange}
                    color="warning"
                    size="small"
                    required
                    input={<OutlinedInput label="Niveaux" />}
                    MenuProps={{
                      PaperProps: {
                        style: {
                          maxHeight: 200,
                          width: 250
                        }
                      }
                    }}
                  >
                    {niveaux.map((niveau) => (
                      <MenuItem key={niveau.niveau_id} value={niveau.niveau_id}>
                        {niveau.nom}
                      </MenuItem>
                    ))}
                  </Select>
                </FormControl>
              </Grid>
            </Grid>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={onClose} color="error">
            Annuler
          </Button>
          <Button type="submit" color="warning">
            Soumettre
          </Button>
        </DialogActions>
      </form>
    </Dialog>
  )
}

export default NiveauMatiere