import React, { useEffect, useState } from 'react'
import {
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  TextField,
  Button,
  InputAdornment
} from '@mui/material'
import { FaTimes } from 'react-icons/fa'

const ModalFormMultiplicateur = ({ open, onClose }) => {
  const [formData, setFormData] = useState({
    id: '',
    multiplicateur: ''
  })

  const [Multiplicateur, setMultiplicateur] = useState(0)

  useEffect(() => {
    window.matieres.getNessesary().then((response) => {
      setMultiplicateur(response)
    })
  }, [])

  useEffect(() => {
    setFormData((prev) => ({
      ...prev,
      id: Multiplicateur.id,
      multiplicateur: Multiplicateur.uniter_heure
    }))
  }, [Multiplicateur])

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

  const handleSubmit = async (e) => {
    e.preventDefault()
    console.log(formData)
    let response = await window.matieres.updateNessesary(formData)

    if (response.success) {
      onClose() // Close the modal after submission
    }
  }

  return (
    <Dialog open={open} onClose={onClose}>
      <form action="" onSubmit={handleSubmit}>
        <DialogTitle>Changer le multiplicateur</DialogTitle>
        <DialogContent>
          <TextField
            autoFocus
            margin="dense"
            required
            name="multiplicateur"
            label="Multiplicateur crédit-heure"
            type="text"
            fullWidth
            variant="outlined"
            value={formData.multiplicateur}
            color="warning"
            onChange={handleChange}
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <FaTimes />
                </InputAdornment>
              )
            }}
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={onClose} color="error">
            Annuler
          </Button>
          <Button type="submit" color="warning">
            Soumettre
          </Button>
        </DialogActions>
      </form>
    </Dialog>
  )
}

export default ModalFormMultiplicateur
