import React, { useEffect, useRef, useState } from 'react'
import classe from '../assets/AllStyleComponents.module.css'
import classeHome from '../assets/Home.module.css'
import { Link, useParams } from 'react-router-dom'
import { IoMdReturnRight } from 'react-icons/io'
import { Box, InputAdornment, Typography, Modal, TextField, Grid, Button } from '@mui/material'
import ChangeCapital from './function/ChangeCapitalLetter'
import { FaClipboardList } from 'react-icons/fa6'
import { IoBookmark } from 'react-icons/io5'
import svgSuccess from '../assets/success.svg'

const SinleMention = () => {
  const { id } = useParams()
  const [mentions, setMention] = useState([])
  const [formData, setFormData] = useState({
    nom: '',
    uniter: '',
    id: ''
  })

  const [errors, setErrors] = useState({
    nom: false,
    uniter: false
  })

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

  useEffect(() => {
    if (mentions) {
      setFormData({
        nom: mentions.nom || '',
        uniter: mentions.uniter || '',
        id: mentions.id || id
      })
    }
  }, [mentions])

  const nomRef = useRef()
  const uniterRef = useRef()

  /**
   * function to set the data in state
   * @param {*} e
   */
  const handleInputChange = (e) => {
    const { name, value } = e.target
    setFormData({
      ...formData,
      [name]: value
    })
    setErrors({
      ...errors,
      [name]: false // Reset the error when user starts typing
    })
  }

  // Helper function to get helperText dynamically
  const getHelperText = (field) => (errors[field] ? 'Ce champ est requis.' : '')

  const formSubmit = async (e) => {
    e.preventDefault()
    const newErrors = {}
    let hasError = false

    // Check for empty fields
    Object.keys(formData).forEach((key) => {
      const value = formData[key]
      if (typeof value === 'string' && !value.trim()) {
        newErrors[key] = true // Set error for empty fields
        hasError = true
      }
    })

    setErrors(newErrors)

    if (!hasError) {
      try {
        let response = await window.mention.updateMention(formData)

        if (response.success) {
          setOpen(true)
        }
      } catch (error) {
        console.log(error)
      }
    }
  }

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

  /**
   * 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
        }}
      >
        <Typography style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
          <img src={svgSuccess} alt="" width={50} height={50} />{' '}
          <span>Mention modifier avec succes</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>
  )

  return (
    <div className={classe.mainHome}>
      {modals()}
      <div className={classeHome.header}>
        <div className={classe.h1style}>
          <div className={classeHome.blockTitle}>
            <h1>Mise a jour mention</h1>
            <div style={{ display: 'flex', gap: '20px' }}>
              <Link to={'/mention'}>
                <Button color="warning" variant="contained">
                  <IoMdReturnRight style={{ fontSize: '20px' }} />
                </Button>
              </Link>
            </div>
          </div>
        </div>
      </div>

      <div className={classeHome.boxEtudiantsCard}>
        <Box
          sx={{
            position: 'absolute',
            top: '55%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            width: 700,
            borderRadius: '2%',
            bgcolor: 'background.paper',
            boxShadow: 24,
            p: 4
          }}
        >
          <Box
            sx={{
              marginTop: '2%',
              display: 'flex',
              width: '100%',
              gap: '20px',
              alignItems: 'start',
              justifyContent: 'center'
            }}
          >
            <form action="" style={{ width: '100%' }} onSubmit={formSubmit}>
              <Grid container spacing={2}>
                <Grid item xs={12} sm={6}>
                  <TextField
                    label="Nom"
                    error={errors.nom}
                    name="nom"
                    color="warning"
                    fullWidth
                    placeholder="GENIE DES MINES"
                    value={formData.nom}
                    onChange={handleInputChange}
                    onInput={() => ChangeCapital(nomRef)}
                    InputProps={{
                      startAdornment: (
                        <InputAdornment position="start">
                          <FaClipboardList />
                        </InputAdornment>
                      )
                    }}
                    helperText={getHelperText('nom')}
                    inputRef={nomRef}
                    sx={{
                      marginBottom: '5px',
                      '& .MuiOutlinedInput-root': {
                        '&:hover fieldset': {
                          borderColor: '#ff9800' // Set the border color on hover
                        }
                      }
                    }}
                  />
                </Grid>
                <Grid item xs={12} sm={6}>
                  <TextField
                    label="Unité"
                    error={errors.uniter}
                    helperText={getHelperText('uniter')}
                    name="uniter"
                    color="warning"
                    fullWidth
                    placeholder="GM"
                    value={formData.uniter}
                    onChange={handleInputChange}
                    onInput={() => ChangeCapital(uniterRef)}
                    InputProps={{
                      startAdornment: (
                        <InputAdornment position="start">
                          <IoBookmark />
                        </InputAdornment>
                      )
                    }}
                    inputRef={uniterRef}
                    sx={{
                      marginBottom: '5px',
                      '& .MuiOutlinedInput-root': {
                        '&:hover fieldset': {
                          borderColor: '#ff9800' // Set the border color on hover
                        }
                      }
                    }}
                  />
                </Grid>
                <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>
  )
}

export default SinleMention
