import React, { useEffect, useRef, useState } from 'react'
import { Link, useParams } from 'react-router-dom'
import { IoMdReturnRight } from 'react-icons/io'
import {
  Box,
  InputAdornment,
  Typography,
  Modal,
  TextField,
  Grid,
  Button,
  Autocomplete
} from '@mui/material'
import { BsBookmarkPlusFill } from 'react-icons/bs'
import svgSuccess from '../assets/success.svg'
import svgError from '../assets/error.svg'
import { MdOutlineNumbers } from 'react-icons/md'
import ChangeCapital from './function/ChangeCapitalLetter'
import { CiCalendar } from 'react-icons/ci'
import { IoBookmark } from 'react-icons/io5'
import { FaClipboardList, FaClock } from 'react-icons/fa'
import classe from '../assets/AllStyleComponents.module.css'
import classeHome from '../assets/Home.module.css'

const SingleMatiere = () => {
  const { id } = useParams()
  const [matiere, setMatiere] = useState(null)
  const [mentions, setMentions] = useState([])
  const [formData, setFormData] = useState({
    nom: '',
    credit: '',
    uniter: '',
    ue: '',
    id: id
  })

  const [message, setMessage] = useState('')
  const [status, setStatus] = useState(200)
  const [open, setOpen] = useState(false)
  const uniterRef = useRef()
  const ueRef = useRef()

  // Helper function to convert a string of IDs to an array
  const stringToArray = (data) => (data ? data.split(',').map(Number) : [])

  useEffect(() => {
    // Fetch single matiere data by ID
    window.matieres.getMatiereByID({ id }).then((response) => {
      setMatiere(response)
    })

    // Fetch mentions data
    window.mention.getMention().then((response) => {
      setMentions(Array.isArray(response) ? response : [])
    })
  }, [id])

  useEffect(() => {
    if (matiere) {
      setFormData((prev) => ({
        ...prev,
        nom: matiere.nom || '',
        credit: matiere.credit || '',
        uniter: matiere.unite_enseignement || '',
        ue: matiere.ue || '',
        id: matiere.id || id
      }))
    }
  }, [matiere, id])

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

  const handleSubmit = async (e) => {
    e.preventDefault()
    const response = await window.matieres.updateMatiere(formData)
    console.log(response)
    if (response.success) {
      setStatus(200)
      setMessage('Modification a été effectuée avec succès')
    } else {
      setStatus(400)
      setMessage('La matière existe déjà dans la base !')
    }
    setOpen(true)
  }

  const handleClose = () => setOpen(false)

  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
          sx={{
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            gap: 2
          }}
        >
          <img src={status === 200 ? svgSuccess : svgError} alt="" width={70} height={70} />
          <span>{message}</span>
        </Typography>
        <Box
          sx={{
            marginTop: 2,
            display: 'flex',
            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 à jour des matières</h1>
            <div style={{ display: 'flex', gap: '20px' }}>
              <Link to="/matiere">
                <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
          }}
        >
          <form onSubmit={handleSubmit} style={{ width: '100%' }}>
            <h4 style={{ textAlign: 'center' }}>Mise à jour</h4>
            <Grid container spacing={2}>
              <Grid item xs={12} sm={6}>
                <TextField
                  label="Nom"
                  name="nom"
                  color="warning"
                  fullWidth
                  value={formData.nom}
                  onChange={handleChange}
                  required
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <BsBookmarkPlusFill />
                      </InputAdornment>
                    )
                  }}
                  sx={{
                    marginBottom: '5px',
                    '& .MuiOutlinedInput-root': {
                      '&:hover fieldset': {
                        borderColor: '#ff9800' // Set the border color on hover
                      }
                    }
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <TextField
                  label="Crédit"
                  name="credit"
                  color="warning"
                  fullWidth
                  placeholder="Crédit pour la matiere"
                  type="number"
                  value={formData.credit}
                  onChange={handleChange}
                  required
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <MdOutlineNumbers />
                      </InputAdornment>
                    )
                  }}
                  inputProps={{ min: 1 }}
                  // inputRef={creditRef}
                  sx={{
                    marginBottom: '5px',
                    '& .MuiOutlinedInput-root': {
                      '&:hover fieldset': {
                        borderColor: '#ff9800' // Set the border color on hover
                      }
                    }
                  }}
                />
              </Grid>
              {/* <Grid item xs={12} sm={6}>
              <TextField
                label="Semestre"
                name="semestre"
                color='warning'
                fullWidth
                placeholder='exemple S1, S2, S3, S4'
                type='text'
                required
                value={formData.semestre}
                onChange={handleChange}
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">
                      <CiCalendar />
                    </InputAdornment>
                  ),
                }}
                inputProps={{ min: 1 }}
                // inputRef={semestreRef}
                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é d'enseignement"
                  name="uniter"
                  color="warning"
                  fullWidth
                  placeholder="Le matiere sera dans quelle unité d'enseignement"
                  value={formData.uniter}
                  onChange={handleChange}
                  onInput={() => ChangeCapital(uniterRef)}
                  required
                  inputRef={uniterRef}
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <IoBookmark />
                      </InputAdornment>
                    )
                  }}
                  inputProps={{ min: 1 }}
                  // inputRef={uniterRef}
                  sx={{
                    marginBottom: '5px',
                    '& .MuiOutlinedInput-root': {
                      '&:hover fieldset': {
                        borderColor: '#ff9800' // Set the border color on hover
                      }
                    }
                  }}
                />
              </Grid>
              <Grid item xs={12} sm={6}>
                <TextField
                  label="UE"
                  name="ue"
                  color="warning"
                  fullWidth
                  placeholder="UE"
                  value={formData.ue}
                  onChange={handleChange}
                  onInput={() => ChangeCapital(ueRef)}
                  inputRef={ueRef}
                  type="text"
                  required
                  InputProps={{
                    startAdornment: (
                      <InputAdornment position="start">
                        <FaClock />
                      </InputAdornment>
                    )
                  }}
                  inputProps={{ min: 1 }}
                  // inputRef={uniterRef}
                  sx={{
                    marginBottom: '5px',
                    '& .MuiOutlinedInput-root': {
                      '&:hover fieldset': {
                        borderColor: '#ff9800' // Set the border color on hover
                      }
                    }
                  }}
                />
              </Grid>
              {/* <Grid item xs={12} sm={6}>
                <Autocomplete
                  multiple
                  options={mentions}
                  getOptionLabel={(option) => option.nom || ''}
                  value={mentions.filter((mention) =>
                    formData.mention_id.includes(mention.id)
                  )}
                  onChange={(event, newValue) => {
                    setFormData((prevData) => ({
                      ...prevData,
                      mention_id: newValue.map((item) => item.id),
                    }));
                  }}
                  isOptionEqualToValue={(option, value) =>
                    option.id === value.id
                  }
                  renderInput={(params) => (
                    <TextField
                      {...params}
                      label="Mentions"
                      color="warning"
                      fullWidth
                      InputProps={{
                        ...params.InputProps,
                        startAdornment: (
                          <>
                            <InputAdornment position="start">
                              <FaClipboardList />
                            </InputAdornment>
                            {params.InputProps.startAdornment}
                          </>
                        ),
                      }}
                      sx={{
                        marginBottom: "5px",
                        '& .MuiOutlinedInput-root': {
                          '&:hover fieldset': {
                            borderColor: '#ff9800', // Set border color on hover
                          },
                        },
                      }}
                    />
                  )}
                />
              </Grid> */}
            </Grid>
            <Box sx={{ textAlign: 'center', marginTop: 2 }}>
              <Button type="submit" color="warning" variant="contained">
                Mettre à jour
              </Button>
            </Box>
          </form>
        </Box>
      </div>
    </div>
  )
}

export default SingleMatiere
