import React, { useEffect, useRef, useState } from 'react'
import classe from '../assets/AllStyleComponents.module.css'
import classeAdd from '../assets/AddStudent.module.css'
import classeHome from '../assets/Home.module.css'
import { Link } from 'react-router-dom'
import { BsBookmarkPlusFill } from 'react-icons/bs'
import {
  FaUserCircle,
  FaBook,
  FaUserCog,
  FaTrash,
  FaPlus,
  FaRegPlusSquare,
  FaNewspaper
} from 'react-icons/fa'
import { Box, Button, InputAdornment, Typography, Modal, TextField, Grid } from '@mui/material'
import Paper from '@mui/material/Paper'
import { createTheme, ThemeProvider } from '@mui/material/styles'
import { DataGrid, GridToolbar } from '@mui/x-data-grid'
import { frFR } from '@mui/x-data-grid/locales'
import { Fa1, Fa2, Fa3, FaM, FaP, FaPenToSquare, FaS } from 'react-icons/fa6'
import { Tooltip } from 'react-tooltip'
import warning from '../assets/warning.svg'
import success from '../assets/success.svg'
import { GiTeacher } from 'react-icons/gi'
import ModalAddProf from './ModalAddProf'
import ParcourMatiere from './ParcourMatiere'
import UpdateModalProf from './UpdateModalProf'
import ModalProcessFichePresence from './ModalProcessFichePresence'
import ModalExportFichr from './ModalExportFichr'
import NiveauMatiere from './NiveauMatiere'

const Matieres = () => {
  const [matiere, setMatiere] = useState([])
  const [openAssignNiveau, setOpenAssignNiveau] = useState(false)
  const [matiereIdAssign, setMatiereIdAssign] = useState(null)
  const [Enseignants, setEnseignants] = useState([])

  useEffect(() => {
    window.matieres.getMatiere().then((response) => {
      setMatiere(response)
    })

    window.matieres.getENseignant().then((response) => {
      setEnseignants(response)
    })
  }, [])

  const theme = createTheme({
    components: {
      MuiIconButton: {
        styleOverrides: {
          root: {
            color: 'gray' // Change the color of toolbar icons
          }
        }
      },
      MuiButton: {
        styleOverrides: {
          root: {
            color: '#121212' // Change the color of toolbar icons
          }
        }
      }
    }
  })

  const openAssignNiveauModal = (id) => {
    setMatiereIdAssign(id)
    setOpenAssignNiveau(true)
  }
  
  const closeAssignNiveauModal = () => {
    setOpenAssignNiveau(false)
    setMatiereIdAssign(null)
  }
  
  const handleNiveauAssignSuccess = (status) => {
    if (status) {
      // Rafraîchir les données des matières et enseignants
      window.matieres.getMatiere().then((response) => {
        setMatiere(response)
      })

      window.matieres.getENseignant().then((response) => {
        setEnseignants(response)
      })
    }
  }

  const [isDeleted, setIsDeleted] = useState(false)
  const [ids, setIds] = useState(0)

  const columns = [
    { field: 'nom', headerName: 'Nom', width: 230 },
    { field: 'credit', headerName: 'Crédit', width: 80 },
    { field: 'heure', headerName: 'Heure', width: 80 },
    { field: 'uniter', headerName: "Unité d'enseignement", width: 180 },
    { field: 'ue', headerName: 'UE', width: 80 },
    { field: 'niveau_id', headerName: 'Niveau', width: 80 },
    { field: 'enseignant', headerName: 'Professeur actuele', width: 230 },
    {
      field: 'action',
      headerName: 'Action',
      width: 600,
      renderCell: (params) => (
        <div style={{ display: 'flex', gap: '10px' }}>
          <Link to={`/singlematiere/${params.value}`}>
            <Button color="warning" variant="contained">
              <FaPenToSquare
                style={{ fontSize: '20px', color: 'white' }}
                className={`update${params.value}`}
              />
              <Tooltip
                anchorSelect={`.update${params.value}`}
                style={{ fontSize: '15px', zIndex: 22 }}
                place="top"
              >
                Modifier
              </Tooltip>
            </Button>
          </Link>
          <Link to={`/asignmatiere/${params.value}`}>
            <Button color="warning" variant="contained">
              <FaM
                className={`asignMention${params.value}`}
                style={{ fontSize: '20px', color: 'white' }}
              />
              <Tooltip
                anchorSelect={`.asignMention${params.value}`}
                style={{ fontSize: '15px', zIndex: 9 }}
                place="top"
              >
                Assigner a un mension
              </Tooltip>
            </Button>
          </Link>
          <Link
        to={`/asignmatieresemestre/${params.value}`}
        className={`sem${params.value}`}
        style={{ textDecoration: 'none' }}
      >
        <Tooltip
          anchorSelect={`.sem${params.value}`}
          style={{ fontSize: '15px', zIndex: 9 }}
          place="top"
        >
          Assigner à un semestre
        </Tooltip>
        <Button color="warning" variant="contained">
          <FaS style={{ fontSize: '20px', color: 'white' }} />
        </Button>
      </Link>

          {/* ----------- BOUTON ASSIGNER NIVEAU ----------- */}
          <Link
            to="#"
            className={`niveau${params.value}`}
            style={{ textDecoration: 'none' }}
            onClick={(e) => {
              e.preventDefault(); // empêche le # de provoquer un scroll
              openAssignNiveauModal(params.value);
            }}
          >
            <Tooltip
              anchorSelect={`.niveau${params.value}`}
              style={{ fontSize: '15px', zIndex: 9 }}
              place="top"
            >
              Assigner à un niveau
            </Tooltip>
            <Button color="warning" variant="contained">
              {/* Icône de ton choix, ici FaRegPlusSquare par exemple */}
              <FaRegPlusSquare style={{ fontSize: '20px', color: 'white' }} />
            </Button>
          </Link>

          <Link
            to="#"
            style={{ textDecoration: 'none' }}
            className={`parcour${params.value}`}
            onClick={() => openParcoursFunction(params.value)}
          >
            <Tooltip
              anchorSelect={`.parcour${params.value}`}
              style={{ fontSize: '15px', zIndex: 9 }}
              place="top"
            >
              Assigner à des parcours
            </Tooltip>
            <Button color="warning" variant="contained">
              <FaP style={{ fontSize: '20px', color: 'white' }} />
            </Button>
          </Link>

          <Link to={`#`}>
            <Button color="warning" variant="contained">
              <GiTeacher
                style={{ fontSize: '20px', color: 'white' }}
                className={`asignProf${params.value}`}
              />
              <Tooltip
                anchorSelect={`.asignProf${params.value}`}
                style={{ fontSize: '15px', zIndex: 22 }}
                place="top"
                clickable
              >
                <Link style={{ zIndex: 99, display: 'flex', alignItems: 'center', gap: '10px' }}>
                  <Button
                    color="warning"
                    variant="contained"
                    onClick={() => openFormModal(params.value)}
                  >
                    <FaPlus
                      style={{ fontSize: '20px', color: 'white' }}
                      className={`adprofModal${params.value}`}
                    />
                    <Tooltip
                      anchorSelect={`.adprofModal${params.value}`}
                      style={{ fontSize: '15px', zIndex: 9 }}
                      place="top"
                    >
                      Ajouter un nouveau professeur
                    </Tooltip>
                  </Button>
                  <Button
                    color="warning"
                    variant="contained"
                    onClick={() => openUppdateProfFunction(params.value)}
                  >
                    <FaPenToSquare
                      style={{ fontSize: '20px', color: 'white' }}
                      className={`updateprofModal${params.value}`}
                    />
                    <Tooltip
                      anchorSelect={`.updateprofModal${params.value}`}
                      style={{ fontSize: '15px', zIndex: 9 }}
                      place="top"
                    >
                      Modifier un professeur
                    </Tooltip>
                  </Button>
                </Link>
              </Tooltip>
            </Button>
          </Link>
          <Link to={`/fiche/${params.value}/${params.row.nom}`}>
            <Tooltip
              anchorSelect={`.presence${params.value}`}
              style={{ fontSize: '15px', zIndex: 22 }}
              place="top"
            >
              Fiche de presence éxamen
            </Tooltip>
            <Button color="warning" variant="contained">
              <FaNewspaper
                style={{ fontSize: '20px', color: 'white' }}
                className={`presence${params.value}`}
              />
            </Button>
          </Link>
          <Link
            to={`#`}
            onClick={() => {
              setIds(params.row.id)
              setOpen(true)
            }}
          >
            <Button color="error" variant="contained">
              <FaTrash
                style={{ fontSize: '20px', color: 'white' }}
                className={`supprimer${params.value}`}
              />
              <Tooltip
                anchorSelect={`.supprimer${params.value}`}
                style={{ fontSize: '15px', zIndex: 22 }}
                place="top"
              >
                Supprimer
              </Tooltip>
            </Button>
          </Link>
        </div>
      )
    }
  ]

  const compareMatieres = (matiere_id) => {
    let NomPrenom = ''
    for (let index = 0; index < Enseignants.length; index++) {
      if (Enseignants[index].matiere_id == matiere_id) {
        NomPrenom = `${Enseignants[index].nom_enseignant} ${Enseignants[index].prenom_enseignant}`
      }
    }

    return NomPrenom
  }

  const paginationModel = { page: 0, pageSize: 5 }

  let dataRow = matiere.map((mat) => ({
    id: mat.id, // Ensure this exists and is unique for each etudiant
    nom: mat.nom,
    credit: mat.credit,
    heure: mat.heure,
    uniter: mat.unite_enseignement,
    ue: mat.ue,
    niveau_id: mat.niveau_nom ?? 'pas de niveau',
    enseignant:
      compareMatieres(mat.id) != '' ? compareMatieres(mat.id) : 'Veuillez assigner un professeur',
    action: mat.id // Ensure this is a valid URL for the image
  }))

  const deleteButton = async (id) => {
    let response = await window.matieres.deleteMatiere(id);
    if (response.success) {
      const updatedMatieres = matiere.filter((matiere) => matiere.id !== id)
      setMatiere(updatedMatieres)
      setIsDeleted(true)
    }
  }

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

  /**
   * function to close modal
   */
  const handleClose = () => {
    setOpen(false)
    setIsDeleted(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
        }}
      >
        {isDeleted ? (
          <Typography
            style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '10px' }}
          >
            <img src={success} alt="" width={50} height={50} /> <span>Suprimer avec succèss</span>
          </Typography>
        ) : (
          <Typography
            style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '10px' }}
          >
            <img src={warning} alt="" width={50} height={50} />{' '}
            <span>Voulez vous supprimer ce matiere ?</span>
          </Typography>
        )}
        <Box
          sx={{
            marginTop: '2%',
            display: 'flex',
            gap: '20px',
            alignItems: 'end',
            justifyContent: 'flex-end'
          }}
        >
          {isDeleted ? (
            <Button onClick={handleClose} color="warning" variant="contained">
              OK
            </Button>
          ) : (
            <div>
              <Button
                onClick={() => deleteButton(ids)}
                sx={{ mr: 1 }}
                color="warning"
                variant="contained"
              >
                Oui
              </Button>
              <Button onClick={handleClose} color="warning" variant="contained">
                Non
              </Button>
            </div>
          )}
        </Box>
      </Box>
    </Modal>
  )

  const [openForm, setOpenForm] = useState(false)
  const [matiereId, setMatiereId] = useState('')
  const [isSubmitted, setIsSubmitted] = useState(false)

  // Callback function to receive the submission status
  const handleFormSubmit = (status) => {
    setIsSubmitted(status)
  }

  useEffect(() => {
    if (isSubmitted) {
      window.matieres
        .getMatiere()
        .then((response) => {
          setMatiere(response)
          setIsSubmitted(false) // Reset isSubmitted after fetching data
        })
        .catch((error) => {
          console.error('Error fetching matiere:', error)
          setIsSubmitted(false) // Ensure reset even on error
        })

      window.matieres.getENseignant().then((response) => {
        setEnseignants(response)
      })
    }
  }, [isSubmitted])

  const closeForm = () => {
    setOpenForm(false)
  }

  const openFormModal = (id) => {
    setOpenForm(true)
    setMatiereId(id)
  }

  const [openParcours, setOpenParcours] = useState(false)
  const onCloseParcours = () => setOpenParcours(false)
  const [idToSend, setIdToSend] = useState(null)
  const openParcoursFunction = (id) => {
    setIdToSend(id)
    setOpenParcours(true)
  }

  const [openUppdateProf, setOpenUpdateProf] = useState(false)
  const onCloseUpdateProf = () => setOpenUpdateProf(false)
  const [idSends, setIdSend] = useState('')
  const openUppdateProfFunction = (id) => {
    setIdSend(id)
    setOpenUpdateProf(true)
  }

  const [openFiche, setOpenFiche] = useState(false)
  const onCloseFiche = () => setOpenFiche(false)
  const [dataFiche, setDataFiche] = useState(null)
  const paperRef = useRef()

  // const extractFiche = async (matiere_id) => {
  //   let response = await
  //   setDataFiche(response)
  // }

  return (
    <div className={classe.mainHome}>
      {modals()}
      <ModalAddProf
        open={openForm}
        onClose={closeForm}
        matiere_id={matiereId}
        onSubmitSuccess={handleFormSubmit}
      />
      <ParcourMatiere matiere_id={idToSend} onClose={onCloseParcours} open={openParcours} />
      <UpdateModalProf
        matiere_id={idSends}
        onClose={onCloseUpdateProf}
        onSubmitSuccess={handleFormSubmit}
        open={openUppdateProf}
      />
      <ModalProcessFichePresence matiere_id={matiereId} onClose={onCloseFiche} open={openFiche} />
      
      {/* Modal NiveauMatiere */}
      <NiveauMatiere
        open={openAssignNiveau}
        onClose={closeAssignNiveauModal}
        matiere_id={matiereIdAssign}
        onSubmitSuccess={handleNiveauAssignSuccess}
      />
      
      <div className={classeAdd.header}>
        <div className={classe.h1style}>
          <div className={classeHome.blockTitle}>
            <h1 style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
              <FaBook />
              Matiere
            </h1>
            <Link to={'/addmatiere'}>
              <Button color="warning" variant="contained">
                <BsBookmarkPlusFill style={{ fontSize: '20px' }} /> AJouter
              </Button>
            </Link>
          </div>
        </div>
      </div>

      {/* displaying data */}
      <div className={classeHome.boxEtudiantsCard}>
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <Paper
            sx={{
              height: 'auto', // Auto height to make the grid responsive
              minHeight: 500, // Ensures a minimum height
              display: 'flex',
              // alignItems: "center",
              // justifyContent: "center",
              width: '100%'
            }}
          >
            <ThemeProvider theme={theme}>
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  flexDirection: 'column', // Stacks content vertically on smaller screens
                  width: '100%'
                }}
              >
                <DataGrid
                  rows={dataRow}
                  columns={columns}
                  initialState={{ pagination: { paginationModel } }}
                  pageSizeOptions={[5, 10]}
                  sx={{
                    border: 0,
                    width: '100%', // Ensures the DataGrid takes full width
                    height: '100%', // Ensures it grows to fit content
                    minHeight: 400, // Minimum height for the DataGrid
                    display: 'flex',
                    justifyContent: 'center',
                    '@media (max-width: 600px)': {
                      width: '100%', // 100% width on small screens
                      height: 'auto' // Allow height to grow with content
                    }
                  }}
                  slots={{ toolbar: GridToolbar }}
                  localeText={frFR.components.MuiDataGrid.defaultProps.localeText}
                />
              </div>
            </ThemeProvider>
          </Paper>
        </div>
      </div>
    </div>
  )
}

export default Matieres