import React, { useEffect, useRef, useState } from 'react'
import { Link, Navigate } from 'react-router-dom'
import classe from '../assets/AllStyleComponents.module.css'
import classeHome from '../assets/Home.module.css'
import Paper from '@mui/material/Paper'
import { Button, InputAdornment, Box, Typography, Modal } from '@mui/material'
import { PiStudentFill } from 'react-icons/pi'
import { DataGrid, GridToolbar } from '@mui/x-data-grid'
import { frFR } from '@mui/x-data-grid/locales'
import dayjs from 'dayjs'
import { FaCertificate, FaGraduationCap, FaPlus, FaReceipt, FaToolbox, FaTrash } from 'react-icons/fa'
import { createTheme, ThemeProvider } from '@mui/material/styles'
import InputLabel from '@mui/material/InputLabel'
import MenuItem from '@mui/material/MenuItem'
import FormControl from '@mui/material/FormControl'
import Select from '@mui/material/Select'
import { Tooltip } from 'react-tooltip'
import { FaPenToSquare, FaFilePdf } from 'react-icons/fa6'
import { CgNotes } from 'react-icons/cg'
import { IoEyeSharp } from 'react-icons/io5'
import PDFEditor from './function/PDFEditor'
import ModalCertificate from './ModalCertificate'
import ModalStage from './ModalStage'
import ModalRecepice from './ModalRecepice'
import { processPdf } from './function/PDFEditorV2'
import { MdVerified } from 'react-icons/md'
import warning from '../assets/warning.svg'
import success from '../assets/success.svg'
import { useAuthContext } from '../contexts/AuthContext' // Import du contexte d'authentification

const Student = () => {
  // Récupération de l'utilisateur connecté
  const { user } = useAuthContext()

  // Fonction pour vérifier si l'utilisateur est admin
  const isAdmin = () => {
    console.log('Rôle de l\'utilisateur dans Student:', user?.roles)
    return user?.roles?.toLowerCase() === 'admin'
  }

  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 [status, setStatus] = useState([])
  const [mention, setMention] = useState([])

  /**
   * hook for displaying the students
   */
  const [etudiants, setEtudiants] = useState([])
  const [notes, setNotes] = useState([])

  useEffect(() => {
    window.etudiants.getEtudiants().then((response) => {
      setEtudiants(response)
    })

    window.notes.getMoyenneVerify().then((response) => {
      setNotes(response)
    })
  }, [])

  const [niveaus, setNiveau] = useState([])

  useEffect(() => {
    window.niveaus.getNiveau().then((response) => {
      setNiveau(response)
    })

    window.statuss.getStatus().then((response) => {
      setStatus(response)
    })

    window.mention.getMention().then((response) => {
      setMention(response)
    })
  }, [])

  // État pour le modal de suppression
  const [openDeleteModal, setOpenDeleteModal] = useState(false)
  const [isDeleted, setIsDeleted] = useState(false)
  const [studentToDelete, setStudentToDelete] = useState(null)

  /**
   * Fonction pour ouvrir le modal de suppression
   */
  const handleOpenDeleteModal = (id) => {
    setStudentToDelete(id)
    setOpenDeleteModal(true)
  }

  /**
   * Fonction pour fermer le modal de suppression
   */
  const handleCloseDeleteModal = () => {
    setOpenDeleteModal(false)
    setIsDeleted(false)
    setStudentToDelete(null)
  }

  /**
   * Fonction de suppression de l'étudiant
   */
  const handleDelete = async () => {
    try {
      const response = await window.etudiants.deleteEtudiant(studentToDelete)
      if (response.success || response) {
        const updatedEtudiants = etudiants.filter((etudiant) => etudiant.id !== studentToDelete)
        setEtudiants(updatedEtudiants)
        setIsDeleted(true)
      }
    } catch (error) {
      console.error("Erreur lors de la suppression :", error)
      // Optionnel: gérer l'erreur avec un état d'erreur
    }
  }

  /**
   * Modal de suppression
   */
  const deleteModal = () => (
    <Modal
      open={openDeleteModal}
      onClose={handleCloseDeleteModal}
      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>Étudiant supprimé avec succès</span>
          </Typography>
        ) : (
          <Typography
            style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '10px' }}
          >
            <img src={warning} alt="" width={50} height={50} />
            <span>Voulez-vous supprimer cet étudiant ?</span>
          </Typography>
        )}
        <Box
          sx={{
            marginTop: '2%',
            display: 'flex',
            gap: '20px',
            alignItems: 'end',
            justifyContent: 'flex-end'
          }}
        >
          {isDeleted ? (
            <Button onClick={handleCloseDeleteModal} color="warning" variant="contained">
              OK
            </Button>
          ) : (
            <div>
              <Button
                onClick={handleDelete}
                sx={{ mr: 1 }}
                color="error"
                variant="contained"
              >
                Oui
              </Button>
              <Button onClick={handleCloseDeleteModal} color="warning" variant="contained">
                Non
              </Button>
            </div>
          )}
        </Box>
      </Box>
    </Modal>
  )

  const SeeNote = ({ params }) => {
    const matchingNote = notes.find(
      (element) =>
        element.etudiant_niveau === params.row.niveau && element.etudiant_id === params.value
    )
    
    return (
      <div style={{ display: 'flex', gap: '10px' }}>
        {matchingNote ? (
          <Link
            to={`/single/notes/${params.value}/${params.row.niveau}/${params.row.annee_scolaire}`}
          >
            <Button color="warning" variant="contained" className={`voirs${params.value}`}>
              <IoEyeSharp style={{ fontSize: '20px', color: 'white' }} />
            </Button>
            <Tooltip anchorSelect={`.voirs${params.value}`} className="custom-tooltip" place="top">
              Voir les notes
            </Tooltip>
          </Link>
        ) : (
          <Link
            to={`/addnotes/${params.value}/${params.row.niveau}/${params.row.mention_id}/${params.row.parcour}`}
          >
            <Button color="warning" variant="contained" className={`note${params.value}`}>
              <CgNotes style={{ fontSize: '20px', color: 'white' }} />
            </Button>
            <Tooltip anchorSelect={`.note${params.value}`} className="custom-tooltip" place="top">
              Ajouter un notes à cet étudiant
            </Tooltip>
          </Link>
        )}
      </div>
    )
  }

  /**
   * function to return the date to local date string
   *
   * @param {string} dateString
   * @returns string
   */
  function formatDate(dateString) {
    // Convert the string to a Date object
    const dateObject = new Date(dateString)

    // Format the date using toLocaleDateString
    const formattedDate = dateObject.toLocaleDateString('fr-FR', {
      day: '2-digit',
      month: 'long',
      year: 'numeric'
    })

    return formattedDate
  }

  /**
   * data column, header of the grid
   */
  const columns = [
    { field: 'nom', headerName: 'Nom', width: 180 },
    { field: 'prenom', headerName: 'Prénom', width: 180 },
    { field: 'sexe', headerName: 'Sexe', width: 80 },
    { field: 'cin', headerName: 'CIN', width: 180 },
    { field: 'date_deli', headerName: 'Date de delivrance', width: 80 },
    { field: 'nation', headerName: 'Natoinalité', width: 120 },
    { field: 'annee_bacc', headerName: 'Année du Baccalauréat', width: 80 },
    { field: 'serie', headerName: 'Série', width: 80 },
    { field: 'bourse', headerName: 'Boursier', width: 80 },
    { field: 'domaine', headerName: 'Domaine', width: 180 },
    { field: 'contact', headerName: 'Contact', width: 180 },
    { field: 'niveau', headerName: 'Niveau', width: 80 },
    { field: 'date_naissance', headerName: 'Date de naissance', width: 130 },
    { field: 'annee_scolaire', headerName: 'Année univarsitaire', width: 130 },
    { field: 'status', headerName: 'Status', width: 140 },
    { field: 'num_inscription', headerName: "Numéro d'inscription", width: 160 },
    { field: 'parcour', headerName: 'Parcours', width: 150 },
    {
      field: 'photos',
      headerName: 'Image',
      width: 100,
      renderCell: (params) => (
        <img
          src={params.value} // Correct the access to the image source
          alt={'image pdp'}
          style={{ width: 50, height: 50, borderRadius: '50%', objectFit: 'cover' }}
        />
      )
    },
    {
      field: 'action',
      headerName: 'Action',
      width: 350,
      renderCell: (params) => (
        <div style={{ display: 'flex', gap: '10px' }}>
          <Link to={`/single/${params.value}`}>
            <Button color="warning" variant="contained">
              <FaPenToSquare
                style={{ fontSize: '20px', color: 'white' }}
                className={`update${params.value}`}
              />
              <Tooltip
                anchorSelect={`.update${params.value}`}
                className="custom-tooltip"
                place="top"
              >
                Modifier
              </Tooltip>
            </Button>
          </Link>
         
          <Link to={`/tranche/${params.value}`} className={`verif${params.value}`}>
            <Button color="warning" variant="contained">
              <MdVerified style={{ fontSize: '20px', color: 'white' }} />
            </Button>
            <Tooltip anchorSelect={`.verif${params.value}`} className="custom-tooltip" place="top">
              Verification Frais de Formation
            </Tooltip>
          </Link>
          <Link onClick={() => Print(params.value)}>
            <Button color="warning" variant="contained" className={`export${params.value}`}>
              <FaFilePdf style={{ fontSize: '20px', color: 'white' }} />
            </Button>
            <Tooltip anchorSelect={`.export${params.value}`} className="custom-tooltip" place="top">
              Exporter carte d'etudiants
            </Tooltip>
          </Link>
          <Link className={`voir${params.value}`}>
            <Button color="warning" variant="contained">
              <FaPlus style={{ fontSize: '20px', color: 'white' }} />
            </Button>
            <Tooltip
              anchorSelect={`.voir${params.value}`}
              style={{
                fontSize: '12px',
                overflow: 'visible',
                zIndex: 999222,
                display: 'flex',
                flexDirection: 'column',
                gap: '10px',
                marginTop: "15px"
              }}
              place="left-end"
              clickable
            >
              {/* Groupe 1 : Certificat */}
              <Link style={{ display: 'flex', gap: '10px' }}>
                {/* Affichage conditionnel de SeeNote - uniquement pour les admins */}
                {isAdmin() && <SeeNote params={params} />}
                
                <Link>
                <Button
                    onClick={() => handleOpen(params.value)}
                    color="warning"
                    variant="contained"
                    className={`receip${params.value}`}
                  >
                    <FaCertificate style={{ fontSize: '20px', color: 'white' }} />
                  </Button>
                  <Tooltip
                    anchorSelect={`.receip${params.value}`}
                    className="custom-tooltip"
                    place="top"
                  >
                    Télecharger le Certificat de scolariter
                  </Tooltip>
                </Link>
              </Link>

              {/* Groupe 2 : Stage (affiché seulement pour L2) */}
              <Link style={{ display: 'flex', gap: '10px' }}>
                {params.row.niveau !== 'L1' && (
                  <Link>
                    <Button
                      onClick={() => handleOpen2()}
                      color="warning"
                      variant="contained"
                      className={`stage${params.value}`}
                    >
                      <FaToolbox style={{ fontSize: '20px', color: 'white' }} />
                    </Button>
                    <Tooltip
                      anchorSelect={`.stage${params.value}`}
                      className="custom-tooltip"
                      place="top"
                    >
                      Télecharger l'autorisation de stage
                    </Tooltip>
                  </Link>
                )}
                <Link>
                  <Button
                    onClick={() => handleOpen3(params.value)}
                    color="warning"
                    variant="contained"
                    className={`recepice${params.value}`}
                  >
                    <FaReceipt style={{ fontSize: '20px', color: 'white' }} />
                  </Button>
                  <Tooltip
                    anchorSelect={`.recepice${params.value}`}
                    className="custom-tooltip"
                    place="top"
                  >
                    Télecharger le recepissé d'inscription
                  </Tooltip>
                </Link>
              </Link>
            </Tooltip>
          </Link>

          
          <Button
  color="error"
  variant="contained"
  onClick={() => handleOpenDeleteModal(params.value)}
  className={`delete${params.value}`}
  sx={{
    marginTop: '10px',
    minWidth: '30px', // largeur mini
    height: '30px',   // hauteur
    padding: '4px',   // espace interne
  }}
>
  <FaTrash style={{ fontSize: '16px', color: 'white' }} />
  <Tooltip
    anchorSelect={`.delete${params.value}`}
    className="custom-tooltip"
    place="top"
  >
    Supprimer
  </Tooltip>
</Button>

          
        </div>
      )
    }
  ]

  const Print = async (id) => {
    console.log(id)
    let etudiant = await window.etudiants.getSingle({ id })

    if (etudiant) {
      let data = {
        f1: `${etudiant.nom} ${etudiant.prenom}`,
        f2: `Naissance: ${dayjs(etudiant.date_de_naissances).format('DD-MM-YYYY')}`,
        f3: `Niveau: ${etudiant.niveau} ${etudiant.mentionUnite}`,
        f4: `Année: ${etudiant.annee_scolaire}`,
        f5: `Inscription: ${etudiant.num_inscription}`,
        f8: etudiant.photos
      }
      processPdf(data)
      // PDFEditor(data);
    }
  }

  // ✅ PAGINATION CORRIGÉE - États pour la pagination complète
  const [paginationModel, setPaginationModel] = useState({
    page: 0,
    pageSize: 20
  })
  const [pageSizeOptions, setPageSizeOptions] = useState([20, 40, 60])

  // ✅ Gestionnaire complet pour les changements de pagination (page ET pageSize)
  const handlePaginationModelChange = (newModel) => {
    console.log('📊 Pagination changed:', newModel) // Pour debug
    
    setPaginationModel(newModel)
    
    // Si l'utilisateur choisit la plus grande option, ajouter +20
    const maxOption = Math.max(...pageSizeOptions)
    if (newModel.pageSize === maxOption) {
      setPageSizeOptions((prev) => [...prev, maxOption + 20])
    }
  }

  // Ensure that the array is flat (not wrapped in another array)
  const dataRow = etudiants.map((etudiant) => ({
    id: etudiant.id, // Ensure this exists and is unique for each etudiant
    nom: etudiant.nom,
    prenom: etudiant.prenom,
    niveau: etudiant.niveau,
    date_naissance: dayjs(etudiant.date_de_naissances).format('DD-MM-YYYY'),
    annee_scolaire: etudiant.annee_scolaire,
    status: comparestatut(etudiant.status),
    num_inscription: etudiant.num_inscription,
    parcour: etudiant.parcours == null ? 'Pas de parcours' : etudiant.parcours,
    photos: etudiant.photos,
    sexe: etudiant.sexe,
    cin: etudiant.cin,
    date_deli: dayjs(etudiant.date_delivrance).format('DD-MM-YYYY'),
    nation: etudiant.nationalite,
    annee_bacc: etudiant.annee_bacc,
    serie: etudiant.serie,
    bourse: etudiant.boursier,
    domaine: etudiant.domaine,
    contact: etudiant.contact,
    mention_id: etudiant.mention_id,
    mentionUnite: etudiant.mentionUnite,
    action: etudiant.id // Ensure this is a valid URL for the image
  }))

  function comparestatut(statutID) {
    let statusText

    status.map((statu) => {
      if (statutID == statu.id) {
        statusText = statu.nom
      }
    })
    return statusText
  }

  /**
   * ✅ Fonction de filtrage avec reset de pagination
   */
  const FilterData = async (e) => {
    let niveau = e.target.value
    if (niveau !== '') {
      let data = await window.etudiants.FilterDataByNiveau({ niveau })
      setEtudiants(data)
      // Reset vers la première page après filtrage
      setPaginationModel(prev => ({ ...prev, page: 0 }))
    } else {
      window.etudiants.getEtudiants().then((response) => {
        setEtudiants(response)
        // Reset vers la première page
        setPaginationModel(prev => ({ ...prev, page: 0 }))
      })
    }
  }

  const [openModal, setOpenModal] = useState(false)
  const [openModal2, setOpenModal2] = useState(false)
  const [openModal3, setOpenModal3] = useState(false)
  const [json, setJson] = useState()
  const [json2, setJson2] = useState()
  const [nom, setNom] = useState([])
  const [nom2, setNom2] = useState([])

  const handleOpen = (id) => {
    window.etudiants.getSingle({ id }).then((response) => {
      setNom(response)
    })
    setOpenModal(true)
  }

  const handleOpen3 = (id) => {
    window.etudiants.getSingle({ id }).then((response) => {
      setNom2(response)
    })
    setOpenModal3(true)
  }

  const handleOpen2 = () => {
    setOpenModal2(true)
  }

  function compareMention(mentionID) {
    let statusText

    mention.map((statu) => {
      if (mentionID == statu.id) {
        statusText = statu.nom
      }
    })

    return statusText ? statusText.charAt(0).toUpperCase() + statusText.slice(1) : statusText
  }

  useEffect(() => {
    setJson({
      nomPrenom: nom.nom + ' ' + nom.prenom,
      naissances: nom.date_de_naissances,
      mention: compareMention(nom.mention_id),
      niveau: nom.niveau,
      annee: nom.annee_scolaire,
      inscri: nom.num_inscription
    })
  }, [nom])

  useEffect(() => {
    setJson2({
      nomPrenom: nom.nom + ' ' + nom.prenom,
      mention: compareMention(nom.mention_id),
      niveau: nom.niveau,
      annee: nom.annee_scolaire,
      inscri: nom.num_inscription
    })
  }, [nom2])

  const handleClose = () => setOpenModal(false)
  const handleClose2 = () => setOpenModal2(false)
  const handleClose3 = () => setOpenModal3(false)

  return (
    <div className={classe.mainHome}>
      {deleteModal()}
      <style>
        {`
        .custom-tooltip {
          font-size: 15px;
          border: solid 1px white !important;
          z-index: 999;
        }
      `}
      </style>
      <div className={classeHome.header}>
        <div className={classe.h1style}>
          <div className={classeHome.blockTitle}>
            <h1>Etudiants</h1>
            <Link to={'/addstudent'}>
              <Button color="warning" variant="contained">
                <PiStudentFill style={{ fontSize: '20px' }} /> Ajouter
              </Button>
            </Link>
          </div>
        </div>
        {/* bare des filtre */}
        <div className={classeHome.container}>
          {/* filtre par niveau */}
          <div style={{ width: '100%', textAlign: 'right' }}>
            <FormControl
              sx={{
                m: 1,
                width: '30%',
                '& .MuiOutlinedInput-root': {
                  '&:hover fieldset': {
                    borderColor: '#ff9800' // Set the border color on hover
                  }
                }
              }}
              size="small"
              variant="outlined"
            >
              <InputLabel
                id="demo-select-small-label"
                sx={{ color: 'black', fontSize: '18px' }}
                color="warning"
              >
                Niveau
              </InputLabel>
              <Select
                labelId="demo-select-small-label"
                id="demo-select-small"
                label="Niveau"
                color="warning"
                name="niveau"
                defaultValue={''}
                onChange={FilterData}
                startAdornment={
                  <InputAdornment position="start">
                    <FaGraduationCap />
                  </InputAdornment>
                }
                sx={{
                  background: 'white',
                  display: 'flex',
                  alignItems: 'center', // Align icon and text vertically
                  '& .MuiSelect-icon': {
                    marginLeft: 'auto' // Keep the dropdown arrow to the right
                  }
                }}
              >
                <MenuItem value="">
                  <em>Tous les étudiants</em>
                </MenuItem>
                {niveaus.map((niveau) => (
                  <MenuItem value={niveau.nom} key={niveau.id}>
                    {niveau.nom}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </div>
        </div>
      </div>

      {/* display the data-grid students */}
      <div className={classeHome.boxEtudiantsCard}>
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <Paper
            sx={{
              width: '100%',
              height: 'auto', // Auto height to make the grid responsive
              minHeight: 500, // Ensures a minimum height
              display: 'flex'
            }}
          >
            <ThemeProvider theme={theme}>
              <div
                style={{
                  display: 'flex',
                  flexDirection: 'column', // Stacks content vertically on smaller screens,
                  width: '100%'
                }}
              >
                <DataGrid
                  rows={dataRow}
                  columns={columns}
                  pageSizeOptions={pageSizeOptions}
                  paginationModel={paginationModel} // ✅ Utilise l'état complet
                  onPaginationModelChange={handlePaginationModelChange} // ✅ Gère page ET pageSize
                  sx={{
                    border: 0,
                    width: 'auto', // Ensures the DataGrid takes full width
                    height: '50%', // 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>
          <ModalCertificate open={openModal} onClose={handleClose} json={json} />
          <ModalStage open={openModal2} onClose={handleClose2} />
          <ModalRecepice open={openModal3} onClose={handleClose3} json={json2} />
        </div>
      </div>
    </div>
  )
}

export default Student