import React, { useRef, useState } from 'react'
import classe from '../assets/AllStyleComponents.module.css'
import img from '../assets/admin.png'
import classeHome from '../assets/Home.module.css'
import { Box, Button, InputAdornment, TextField, Grid, Typography, Modal } from '@mui/material'
import classeAdd from '../assets/AddStudent.module.css'
import validationAddAdmin from './validation/AddAdmin'
import svgSuccess from '../assets/success.svg'
import svgError from '../assets/error.svg'
import { FaEnvelope, FaLock, FaUser } from 'react-icons/fa'

const Admin = () => {
  const [formData, setFormData] = useState({
    username: '',
    email: '',
    password: '',
    roles: 'Enseignant'
  })

  const usernameRef = useRef()
  const emailRef = useRef()
  const passwordRef = useRef()
  const rolesRef = useRef()
  const errorUsername = useRef()
  const errorEmail = useRef()
  const errorPassword = useRef()

  /**
   * function to set the data in state
   * @param {*} e
   */
  const handleInputChange = (e) => {
    const { name, value } = e.target
    setFormData((prevData) => ({
      ...prevData,
      [name]: value
    }))
  }

  const handleSubmit = async (e) => {
    e.preventDefault()
    // Handle form submission logic
    const valid = validationAddAdmin(
      usernameRef.current,
      emailRef.current,
      passwordRef.current,
      errorUsername.current,
      errorEmail.current,
      errorPassword.current
    )
    console.log(formData)
    console.log(valid)

    if (valid) {
      const response = await window.allUser.insertUsers(formData)
      console.log(response)
      if (response.success) {
        setOpen(true)
        setFormData({
          username: '',
          email: '',
          password: '',
          roles: 'Enseignant'
        })
      }

      if (response.code) {
        setCode(422)
        setOpen(true)
      }
    }
  }

  /**
   * hook to open modal
   */
  const [open, setOpen] = useState(false)
  const [code, setCode] = useState(200)

  /**
   * function to close modal
   */
  const handleClose = () => setOpen(false)

  /**
   * function to return the view Modal
   *
   * @returns {JSX}
   */
  const modals = () => (
    <Modal
      open={open}
      onClose={handleClose}
      aria-labelledby="modal-title"
      aria-describedby="modal-description"
    >
      <Box
        sx={{
          position: 'absolute',
          top: '50%',
          left: '50%',
          transform: 'translate(-50%, -50%)',
          width: 450,
          bgcolor: 'background.paper',
          boxShadow: 24,
          p: 4
        }}
      >
        {code == 422 ? (
          <Typography
            style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '10px' }}
          >
            <img src={svgError} alt="" width={50} height={50} />{' '}
            <span style={{ marginLeft: '10px' }}>Email déjà pris</span>
          </Typography>
        ) : (
          <Typography
            style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '10px' }}
          >
            <img src={svgSuccess} alt="" width={50} height={50} />{' '}
            <span>Insertion a été effectuée avec succès</span>
          </Typography>
        )}
        <Box
          sx={{
            marginTop: '2%',
            display: 'flex',
            gap: '20px',
            alignItems: 'end',
            justifyContent: 'flex-end'
          }}
        >
          <Button onClick={handleClose} color="warning" variant="contained">
            OK
          </Button>
        </Box>
      </Box>
    </Modal>
  )

  const sendData = async () => {
    await window.syncro.getall()
  }

  return (
    <div className={classe.mainHome}>
      {modals()}
      <div className={classeHome.header}>
        <div className={classe.h1style}>
          <div className={classeHome.blockTitle}>
            <h1>Ajout d'admin</h1>
            <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
              <Button color="warning" variant="contained">
                Recevoir une mise à jour au server
              </Button>
              <Button color="warning" variant="contained" onClick={sendData}>
                Envoyer une mise à jour au server
              </Button>
            </div>
          </div>
        </div>
      </div>
      {/* contenu */}
      <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={{
                marginTop: '5%',
                display: 'flex',
                gap: '10px',
                alignItems: 'start',
                flexDirection: 'column',
                fontSize: 16,
                fontFamily: 'sans-serif',
                justifyContent: 'flex-end'
              }}
            >
              <span style={{ display: 'flex', marginLeft: '40%' }}>
                <img src={img} alt="" height={150} width={150} />
              </span>

              <form onSubmit={handleSubmit} style={{ marginTop: '5%' }}>
                <Grid container spacing={2}>
                  {/* matieres Algebre */}
                  <Grid item xs={12} sm={6}>
                    <TextField
                      label="username"
                      name="username"
                      color="warning"
                      fullWidth
                      value={formData.username}
                      onChange={handleInputChange}
                      InputProps={{
                        startAdornment: (
                          <InputAdornment position="start">
                            <FaUser />
                          </InputAdornment>
                        )
                      }}
                      inputRef={usernameRef}
                      sx={{
                        '& .MuiOutlinedInput-root': {
                          '&:hover fieldset': {
                            borderColor: '#ff9800' // Set the border color on hover
                          }
                        }
                      }}
                    />
                    {/* error username */}
                    <span
                      className="text-danger"
                      ref={errorUsername}
                      style={{ fontSize: '13px' }}
                    ></span>
                  </Grid>
                  {/* matieres Analyse */}
                  <Grid item xs={12} sm={6}>
                    <TextField
                      label="email"
                      name="email"
                      fullWidth
                      color="warning"
                      value={formData.email}
                      onChange={handleInputChange}
                      InputProps={{
                        startAdornment: (
                          <InputAdornment position="start">
                            <FaEnvelope />
                          </InputAdornment>
                        )
                      }}
                      inputRef={emailRef}
                      sx={{
                        '& .MuiOutlinedInput-root': {
                          '&:hover fieldset': {
                            borderColor: '#ff9800' // Set the border color on hover
                          }
                        }
                      }}
                    />
                    {/* error email */}
                    <span
                      className="text-danger"
                      style={{ fontSize: '13px' }}
                      ref={errorEmail}
                    ></span>
                  </Grid>
                  {/* matieres Mecanique general */}
                  <Grid item xs={12} sm={6}>
                    <TextField
                      label="password"
                      name="password"
                      fullWidth
                      color="warning"
                      value={formData.password}
                      onChange={handleInputChange}
                      InputProps={{
                        startAdornment: (
                          <InputAdornment position="start">
                            <FaLock />
                          </InputAdornment>
                        )
                      }}
                      inputRef={passwordRef}
                      sx={{
                        '& .MuiOutlinedInput-root': {
                          '&:hover fieldset': {
                            borderColor: '#ff9800' // Set the border color on hover
                          }
                        }
                      }}
                    />
                    {/* error password */}
                    <span
                      className="text-danger"
                      ref={errorPassword}
                      style={{ fontSize: '13px' }}
                    ></span>
                  </Grid>
                  {/* Matieres Resistance Materiaux */}
                  <Grid item xs={12} sm={6}>
                    <TextField
                      label="roles"
                      name="roles"
                      fullWidth
                      color="warning"
                      value={formData.roles}
                      onChange={handleInputChange}
                      disabled
                      InputProps={{
                        startAdornment: <InputAdornment position="start"></InputAdornment>
                      }}
                      inputRef={rolesRef}
                      sx={{
                        '& .MuiOutlinedInput-root': {
                          '&:hover fieldset': {
                            borderColor: '#ff9800' // Set the border color on hover
                          }
                        }
                      }}
                    />
                  </Grid>
                  {/* Submit Button */}
                  <Grid
                    item
                    xs={12}
                    style={{ display: 'flex', gap: '30px', justifyContent: 'flex-end' }}
                  >
                    <Button type="submit" color="warning" variant="contained">
                      Enregister
                    </Button>
                  </Grid>
                </Grid>
              </form>
            </Box>
          </Box>
        </div>
      </div>
    </div>
  )
}

export default Admin
