import React, { useEffect, useState } from 'react'
import { Link, useParams } from 'react-router-dom'
import { FaPlus } from 'react-icons/fa'
import { Button, Grid, Paper, Checkbox, Modal, Typography, Box } from '@mui/material'
import { IoMdReturnRight } from 'react-icons/io'
import classe from '../assets/AllStyleComponents.module.css'
import classeAdd from '../assets/AddStudent.module.css'
import classeHome from '../assets/Home.module.css'
import svgSuccess from '../assets/success.svg'

const AssignMatiereToMention = () => {
  let { id } = useParams()

  const [mention, setMention] = useState([])
  const [matiere, setMatiere] = useState({})
  const [matiereMention, setMatiereMention] = useState([])
  const [formData, setFormData] = useState({})

  // Fetch data on component mount
  useEffect(() => {
    window.matieres.getAsign({ id }).then((response) => {
      setMatiereMention(response) // Set matiereMention
    })
    window.mention.getMention().then((response) => {
      setMention(response) // Set mention
    })
    window.matieres.getMatiereByID({ id }).then((response) => {
      setMatiere(response) // Set matiere
    })
  }, [id])

  // Initialize formData based on mentions and matiereMention
  useEffect(() => {
    if (mention.length && matiereMention.length) {
      const initialFormData = mention.reduce((acc, mens) => {
        // Check if the current mention ID exists in matiereMention
        const isChecked = matiereMention.some((item) => item.mention_id === mens.id)
        acc[mens.id] = isChecked // Set true if matched, false otherwise
        return acc
      }, {})
      setFormData(initialFormData) // Update formData
    }
  }, [mention, matiereMention])

  /**
   * Handle form submission
   */
  const formSubmit = async (e) => {
    e.preventDefault()

    let response = await window.matieres.asign({ formData, id })
    console.log(response)
    if (response.success) {
      setOpen(true)
    }
  }

  /**
   * Handle checkbox change
   */
  const handleCheckboxChange = (id) => {
    setFormData((prevData) => ({
      ...prevData,
      [id]: !prevData[id] // Toggle the checkbox value
    }))
  }

  /**
   * 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', alignItems: 'center', flexDirection: 'column' }}>
          <img src={svgSuccess} alt="" width={50} height={50} />{' '}
          <span>Changemet 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>
  )

  return (
    <div className={classe.mainHome}>
      {modals()}
      <div className={classeAdd.header}>
        <div className={classe.h1style}>
          <div className={classeHome.blockTitle}>
            <h1 style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
              <FaPlus /> Asignation
            </h1>
            <Link to={'#'} onClick={() => window.history.back()}>
              <Button color="warning" variant="contained">
                <IoMdReturnRight style={{ fontSize: '20px' }} />
              </Button>
            </Link>
          </div>
        </div>
      </div>

      <Paper
        sx={{
          height: 'auto',
          minHeight: 500,
          display: 'flex',
          width: '100%'
        }}
      >
        <form style={{ width: '100%', padding: '2%' }} onSubmit={formSubmit}>
          <h5 style={{ textAlign: 'center', textDecoration: 'underline' }}>
            Choisissez les mentions qui utilisent {matiere?.nom || 'la matière'}
          </h5>
          <Grid container spacing={2}>
            {mention.map((mens) => (
              <Grid
                item
                xs={12}
                sm={3}
                sx={{
                  display: 'flex',
                  justifyContent: 'space-between',
                  alignItems: 'center',
                  padding: 5
                }}
                key={mens.id}
              >
                <span>
                  <b>
                    <i>{mens.nom}</i>
                  </b>
                </span>
                <span>
                  <Checkbox
                    checked={formData[mens.id] || false} // Bind checkbox to formData
                    onChange={() => handleCheckboxChange(mens.id)} // Handle change
                    color="success"
                  />
                </span>
              </Grid>
            ))}
          </Grid>
          <Grid
            item
            xs={12}
            style={{
              display: 'flex',
              gap: '30px',
              justifyContent: 'flex-end'
            }}
          >
            <Button type="submit" color="warning" variant="contained">
              Enregistrer
            </Button>
          </Grid>
        </form>
      </Paper>
    </div>
  )
}

export default AssignMatiereToMention
