import { useState } from 'react'
import { Box, Button, InputAdornment, TextField, Grid, Modal, Typography } from '@mui/material'
import { FaEnvelope, FaLock, FaUser } from 'react-icons/fa'
import { GrConfigure } from 'react-icons/gr'
import { Link } from 'react-router-dom'
import { useAuthContext } from '../contexts/AuthContext'
import IpConfig from './IpConfig'
import classe from '../assets/AllStyleComponents.module.css'
import classeHome from '../assets/Home.module.css'
import classeAdd from '../assets/AddStudent.module.css'
import img from '../assets/para.png'
import svgSuccess from '../assets/success.svg'
import svgError from '../assets/error.svg'
import { useNavigate} from 'react-router-dom'

const Setting = () => {
  const { user, setUser, token, setToken } = useAuthContext()

  const navigate = useNavigate() 
  if (!user) {
    navigate('/login');
    return <div>Chargement...</div>
  }
  // Initialisation du formulaire avec les infos de l'utilisateur
  const [formData, setFormData] = useState({
    username: user.username,
    email: user.email,
    password: '',
    id: user.id
  })

  // Gestion des inputs
  const handleInputChange = (e) => {
    const { name, value } = e.target
    setFormData((prevData) => ({
      ...prevData,
      [name]: value
    }))
  }

  // Gestion de l'envoi du formulaire
  const handleSubmit = async (e) => {
    e.preventDefault()
    try {
      const response = await window.allUser.updateUsers(formData)
      if (response.success) {
        setOpen(true)
        setCode(200)
        setUser(response.user)        // Mettre à jour user
        setToken(response.user.token) // Mettre à jour token si besoin
        setFormData({
          username: response.user.username,
          email: response.user.email,
          password: '',
          id: response.user.id
        })
      } else {
        setCode(422)
        setOpen(true)
      }
    } catch (error) {
      console.error('Erreur lors de la mise à jour:', error)
      setCode(500)
      setOpen(true)
    }
  }

  // Modal
  const [open, setOpen] = useState(false)
  const [code, setCode] = useState(200)
  const handleClose = () => setOpen(false)

  const modals = () => (
    <Modal open={open} onClose={handleClose} aria-labelledby="modal-title">
      <Box
        sx={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          width: 450,
          bgcolor: 'background.paper',
          boxShadow: 24,
          p: 4
        }}
      >
        {code === 422 ? (
          <Typography sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '10px' }}>
            <img src={svgError} alt="Erreur" width={50} height={50} />
            <span>Email déjà pris</span>
          </Typography>
        ) : code === 500 ? (
          <Typography sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '10px' }}>
            <span>Une erreur est survenue</span>
          </Typography>
        ) : (
          <Typography sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '10px' }}>
            <img src={svgSuccess} alt="Succès" width={100} height={100} />
            <span>Modification effectuée avec succès</span>
          </Typography>
        )}
        <Box sx={{ mt: 2, display: 'flex', justifyContent: 'flex-end' }}>
          <Button onClick={handleClose} color="warning" variant="contained">
            OK
          </Button>
        </Box>
      </Box>
    </Modal>
  )

  // IP Config
  const [openConfig, setOpenConfig] = useState(false)
  const onCloseConfig = () => setOpenConfig(false)
  const openConfigFunction = () => setOpenConfig(true)

  return (
    <div className={classe.mainHome}>
      {modals()}
      <IpConfig onClose={onCloseConfig} open={openConfig} />
      <div className={classeHome.header}>
        <div className={classe.h1style}>
          <div className={classeHome.blockTitle}>
            <h1>Settings</h1>
            <Link to="#" onClick={openConfigFunction}>
              <Button color="warning" variant="contained">
                <GrConfigure style={{ fontSize: '20px' }} /> IP configuration
              </Button>
            </Link>
          </div>
        </div>
      </div>

      <div className={classeHome.contenaire}>
        <div className={classeAdd.boxEtudiantsCard}>
          <Box
            sx={{
              position: 'absolute',
              top: '50%',
              left: '50%',
              transform: 'translate(-50%, -50%)',
              width: 700,
              borderRadius: '3%',
              bgcolor: 'background.paper',
              boxShadow: 24,
              p: 4
            }}
          >
            <Box
              sx={{
                mt: '5%',
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                gap: '10px'
              }}
            >
              <img src={img} alt="avatar" width={150} height={150} />
              <form onSubmit={handleSubmit} style={{ width: '100%', marginTop: '5%' }}>
                <Grid container spacing={2}>
                  <Grid item xs={12} sm={6}>
                    <TextField
                      label="Nom d'utilisateur"
                      name="username"
                      color="warning"
                      fullWidth
                      value={formData.username}
                      onChange={handleInputChange}
                      required
                      InputProps={{
                        startAdornment: <InputAdornment position="start"><FaUser /></InputAdornment>
                      }}
                    />
                  </Grid>
                  <Grid item xs={12} sm={6}>
                    <TextField
                      label="Email"
                      name="email"
                      fullWidth
                      required
                      color="warning"
                      value={formData.email}
                      onChange={handleInputChange}
                      InputProps={{
                        startAdornment: <InputAdornment position="start"><FaEnvelope /></InputAdornment>
                      }}
                    />
                  </Grid>
                  <Grid item xs={12}>
                    <TextField
                      label="Mot de passe"
                      name="password"
                      fullWidth
                      helperText="À laisser vide si vous ne voulez pas le modifier"
                      color="warning"
                      value={formData.password}
                      onChange={handleInputChange}
                      InputProps={{
                        startAdornment: <InputAdornment position="start"><FaLock /></InputAdornment>
                      }}
                    />
                  </Grid>
                  <Grid item xs={12} sx={{ display: 'flex', justifyContent: 'flex-end' }}>
                    <Button type="submit" color="warning" variant="contained">
                      Enregistrer
                    </Button>
                  </Grid>
                </Grid>
              </form>
            </Box>
          </Box>
        </div>
      </div>
    </div>
  )
}

export default Setting
