import React, { useState } from 'react'
import { TextField, InputAdornment, Button } from '@mui/material'
import { FaUser } from 'react-icons/fa'

const AddStudentForm = () => {
  const [formData, setFormData] = useState({ nom: '' })
  const [errors, setErrors] = useState({ nom: '' })

  const handleInputChange = (e) => {
    const { name, value } = e.target

    // Set the form data
    setFormData((prevData) => ({
      ...prevData,
      [name]: value
    }))

    // Clear errors when the user starts typing again
    setErrors((prevErrors) => ({
      ...prevErrors,
      [name]: '' // Clear the error for the specific field
    }))
  }

  const validate = () => {
    let valid = true
    let newErrors = {}

    // Example validation for "nom" field (it must not be empty)
    if (!formData.nom.trim()) {
      newErrors.nom = 'Nom is required'
      valid = false
    }

    setErrors(newErrors)
    return valid
  }

  const handleSubmit = (e) => {
    e.preventDefault()

    // Validate the form
    if (validate()) {
      // Form is valid, handle the submission logic
      console.log(formData)
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <TextField
        label="Nom"
        name="nom"
        color="secondary"
        fullWidth
        value={formData.nom}
        onChange={handleInputChange}
        error={Boolean(errors.nom)} // This makes the field red if there's an error
        helperText={errors.nom} // This displays the error message below the field
        InputProps={{
          startAdornment: (
            <InputAdornment position="start">
              <FaUser />
            </InputAdornment>
          )
        }}
      />

      <Button type="submit" variant="contained" color="primary" style={{ marginTop: 20 }}>
        Submit
      </Button>
    </form>
  )
}

export default AddStudentForm
