import React, { useEffect, useRef, useState } from 'react'
import {
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  TextField,
  Button,
  Autocomplete,
  InputAdornment,
  Box,
  Grid
} from '@mui/material'
import { MdRule } from 'react-icons/md'
import { FaClipboardList } from 'react-icons/fa'

const AddParcours = ({ open, onClose, onSubmitSuccess }) => {
  const [formData, setFormData] = useState({
    nom: '',
    uniter: '',
    mention_id: null
  })

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

  useEffect(() => {
    window.mention.getMention().then((response) => {
      setMention(response)
    })
  }, [])

  const handleChange = (e) => {
    const { name, value } = e.target
    setFormData({ ...formData, [name]: value })
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    let response = await window.notesysteme.insertParcours(formData)
    console.log(response) 
    if (response.success) {
      onSubmitSuccess(true)
      onClose() // Close the modal after submission
      setFormData({
        nom: '',
        uniter: '',
        mention_id: null
      })
    }
  }

  return (
    <Dialog open={open} onClose={onClose}>
      <form action="" onSubmit={handleSubmit}>
        <DialogTitle>Information sur le parcour</DialogTitle>
        <DialogContent>
          <Box sx={{ flexGrow: 1 }}>
            <Grid container spacing={2}>
              <Grid item xs={12} sm={6}>
                <TextField
                  autoFocus
                  margin="normal"
                  required
                  name="nom"
                  label="Nom du parcours"
                  type="text"
                  fullWidth
                  placeholder="Nom du parcours"
                  variant="outlined"
                  value={formData.nom}
                  color="warning"
                  onChange={handleChange}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <MdRule />
                      </InputAdornment>
                    )
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <TextField
                  autoFocus
                  margin="normal"
                  required
                  name="uniter"
                  label="Uniter parcours"
                  type="text"
                  fullWidth
                  placeholder="GPESB"
                  variant="outlined"
                  value={formData.uniter}
                  color="warning"
                  onChange={handleChange}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <MdRule />
                      </InputAdornment>
                    )
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={12}>
                <Autocomplete
                  options={mention} // Options array for Autocomplete
                  getOptionLabel={(option) => option.nom || ''} // Safely access `nom`
                  value={mention.find((item) => item.id === formData.mention_id) || null} // Bind selected value to form data
                  onChange={(event, newValue) => {
                    setFormData((prevData) => ({
                      ...prevData,
                      mention_id: newValue ? newValue.id : null // Store the ID of the selected mention
                    }))
                  }}
                  isOptionEqualToValue={(option, value) => option.id === value.id} // Ensure correct matching of options
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      label="Mention"
                      color="warning"
                      placeholder="Sélectionnez une mention"
                      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>
          </Box>
        </DialogContent>
        <DialogActions>
          <Button onClick={onClose} color="error">
            Annuler
          </Button>
          <Button type="submit" color="warning">
            Soumettre
          </Button>
        </DialogActions>
      </form>
    </Dialog>
  )
}

export default AddParcours
