import React, { useEffect, useState } from 'react'
import { useParams, Link } 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 { DataGrid, GridToolbar } from '@mui/x-data-grid'
import { frFR } from '@mui/x-data-grid/locales'
import { createTheme, ThemeProvider } from '@mui/material/styles'
import { IoNewspaperOutline } from 'react-icons/io5'
import { IoMdReturnRight } from 'react-icons/io'
import { Button, Modal, Box, Menu, MenuItem } from '@mui/material'
import { Tooltip } from 'react-tooltip'
import ReleverNotes from './ReleverNotes'
import { FaDownload } from 'react-icons/fa'

const Noteclasse = () => {
  const { niveau, scolaire } = useParams()

  const [etudiants, setEtudiants] = useState([])
  const [mention, setMention] = useState([])
  const [session, setSession] = useState([])

  const formData = {
    niveau,
    scolaire
  }

  useEffect(() => {
    window.notes.getMoyenne(formData).then((response) => {
      setEtudiants(response)
    })
    window.noteRepech.getMoyenneRepech(formData).then((response) => {
      setSession(response)
    })
    window.mention.getMention().then((response) => {
      setMention(response)
    })
  }, [])

  let dataToMap = []

  function returnmention(id) {
    let mentions
    for (let index = 0; index < mention.length; index++) {
      if (mention[index].id == id) {
        mentions = mention[index].nom
      }
    }
    return mentions
  }

  function checkNull(params) {
    console.log(params);
    if (params == null || params == undefined) {
      return null
    }
    return params
  }

  // MODIFICATION: Nouvelle fonction pour calculer la moyenne avec rattrapage
  function compareSessionNotesForAverage(session1, session2) {
    // Si il y a une session de rattrapage, utiliser la meilleure note
    if (session2) {
      return Math.max(session1, session2.note)
    }
    // Sinon utiliser la note normale
    return session1
  }

  function compareSessionNotes(session1, session2) {
    let notes
    if (session2) {
      if (session1 < session2.note) {
        notes = session2.note
      } else {
        notes = session1
      }
    } else {
      notes = session1
    }
    return notes
  }

  for (let index = 0; index < etudiants.length; index++) {
    let total = 0
    let note = 0
    let totalCredit = 0

    // Create a new object for each student
    let modelJson = {
      id: '',
      nom: '',
      prenom: '',
      photos: '',
      moyenne: '',
      mention: '',
      anneescolaire: ''
    }

    for (let j = 0; j < etudiants[index].length; j++) {
      modelJson.id = etudiants[index][j].etudiant_id
      modelJson.nom = etudiants[index][j].nom
      modelJson.prenom = etudiants[index][j].prenom
      modelJson.photos = etudiants[index][j].photos
      modelJson.mention = etudiants[index][j].mention_id
      modelJson.anneescolaire = etudiants[index][j].annee_scolaire

      // MODIFICATION: Utiliser la meilleure note (rattrapage si existe) pour la moyenne générale
      if (session[index]) {
        note +=
          compareSessionNotesForAverage(etudiants[index][j].note, checkNull(session[index][j])) *
          etudiants[index][j].credit
      } else {
        note += etudiants[index][j].note * etudiants[index][j].credit
      }
      totalCredit += etudiants[index][j].credit
    }

    total = note / totalCredit
    modelJson.moyenne = total.toFixed(2)

    // Add the new object to the array
    dataToMap.push(modelJson)
  }

  function checkNumberSession(id) {
    let sessionNumber = 1
    for (let index = 0; index < session.length; index++) {
      for (let j = 0; j < session[index].length; j++) {
        if (session[index][j].etudiant_id == id) {
          sessionNumber = 2
          break
        }
      }
      if (sessionNumber === 2) break
    }
    return sessionNumber
  }

  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 paginationModel = { page: 0, pageSize: 5 }

  // États pour le menu déroulant
  const [anchorEl, setAnchorEl] = useState(null)
  const [selectedStudentId, setSelectedStudentId] = useState(null)
  const open = Boolean(anchorEl)

  const handleMenuClick = (event, studentId) => {
    setAnchorEl(event.currentTarget)
    setSelectedStudentId(studentId)
  }

  const handleMenuClose = () => {
    setAnchorEl(null)
    setSelectedStudentId(null)
  }

  const handleSessionTypeSelect = (sessionType) => {
    sendData(selectedStudentId, sessionType)
    handleMenuClose()
  }

  const columns = [
    { field: 'nom', headerName: 'Nom', width: 170 },
    { field: 'prenom', headerName: 'Prénom', width: 160 },
    { field: 'session', headerName: 'Nombre de Session', width: 180 },
    { field: 'mention', headerName: 'Mention', width: 180 },
    { field: 'moyenne', headerName: 'Moyenne Général', width: 160 },
    {
      field: 'photos',
      headerName: 'Photos',
      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',
      flex: 1,
      renderCell: (params) => (
        <div style={{ display: 'flex', gap: '10px' }}>
          <Button 
            color="warning" 
            variant="contained" 
            className={`update${params.value}`}
            onClick={(event) => handleMenuClick(event, params.value)}
          >
            <IoNewspaperOutline style={{ fontSize: '20px', color: 'white' }} />
          </Button>
          <Tooltip
            anchorSelect={`.update${params.value}`}
            style={{ fontSize: '13px', zIndex: 22 }}
            place="bottom-end"
          >
            Imprimer un relevé de notes
          </Tooltip>
        </div>
      )
    }
  ]

  const dataTable = dataToMap.map((data) => ({
    id: data.id,
    nom: data.nom,
    prenom: data.prenom,
    photos: data.photos,
    mention: returnmention(data.mention),
    session: checkNumberSession(data.id),
    moyenne: data.moyenne,
    action: data.id
  }))

  const [openCard, setOpenCart] = useState(false)
  const [bolll, setBolll] = useState(false)
  const [form, setForm] = useState({
    id: '',
    niveau: '',
    anneescolaire: '',
    sessionType: 'ensemble' // Par défaut
  })
  const [selectedId, setSelectedId] = useState(null) // Store id dynamically

  const sendData = (id, sessionType = 'ensemble') => {
    setSelectedId(id)
    setForm(prevForm => ({
      ...prevForm,
      sessionType: sessionType
    }))
    setOpenCart(true)
  }

  useEffect(() => {
    if (selectedId !== null) {
      const foundData = dataToMap.find((item) => item.id === selectedId)
      if (foundData) {
        setForm((prevForm) => ({
          ...prevForm,
          id: foundData.id,
          anneescolaire: foundData.anneescolaire,
          niveau: niveau
        })) // Update form with the found object
      }
    }
  }, [openCard, selectedId])
  
  console.log(form)
  
  const downloadButton = () => {
    setBolll(true)
  }

  /**
   * function to close modal
   */
  const handleCloseCart = () => {
    setBolll(false)
    setOpenCart(false)
  }

  const modalReleverNotes = () => {
    return (
      <Modal
        open={openCard}
        onClose={handleCloseCart}
        aria-labelledby="modal-title"
        aria-describedby="modal-description"
        sx={{
          overflow: 'auto'
        }}
      >
        <Box
          sx={{
            boxShadow: 24,
            p: 4,
            overflow: 'auto',
            position: 'relative'
          }}
        >
          <ReleverNotes
            id={form.id}
            anneescolaire={scolaire}
            niveau={form.niveau}
            sessionType={form.sessionType}
            refs={bolll}
          />
          <Button
            color="warning"
            variant="contained"
            onClick={downloadButton}
            sx={{ position: 'absolute', top: '2%', right: '10%' }}
          >
            <FaDownload />
            Télécharger
          </Button>
          <button
            style={{
              position: 'absolute',
              top: '2.5%',
              right: '23%',
              border: 'none',
              background: 'orange',
              outline: 'none',
              borderRadius: '100px'
            }}
            onClick={handleCloseCart}
          >
            X
          </button>
        </Box>
      </Modal>
    )
  }

  return (
    <div className={classe.mainHome}>
      {modalReleverNotes()}
      
      {/* Menu pour sélectionner le type de session */}
      <Menu
        anchorEl={anchorEl}
        open={open}
        onClose={handleMenuClose}
        MenuListProps={{
          'aria-labelledby': 'session-button',
        }}
      >
        <MenuItem onClick={() => handleSessionTypeSelect('normale')}>
          Session Normale
        </MenuItem>
        <MenuItem onClick={() => handleSessionTypeSelect('ensemble')}>
          Session Rattrapage
        </MenuItem>
      </Menu>

      <div className={classeHome.header}>
        <div className={classe.h1style}>
          <div className={classeHome.blockTitle}>
            <h1>
              Notes des {niveau} en {scolaire}
            </h1>
            <div style={{ display: 'flex', gap: '10px' }}>
              <Link to={`/resultat/${niveau}/${scolaire}`}>
                <Button color="warning" variant="contained">
                  Resultat
                </Button>
              </Link>
              <Link to={'#'} onClick={() => window.history.back()}>
                <Button color="warning" variant="contained">
                  <IoMdReturnRight style={{ fontSize: '20px' }} />
                </Button>
              </Link>
            </div>
          </div>
        </div>
      </div>

      <div className={classeHome.boxEtudiantsCard}>
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <Paper
            sx={{
              height: 'auto', // Auto height to make the grid responsive
              width: '100%',
              minHeight: 500, // Ensures a minimum height
              display: 'flex'
            }}
          >
            <ThemeProvider theme={theme}>
              <div
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  width: '100%', // Make it responsive to full width
                  flexDirection: 'column' // Stacks content vertically on smaller screens
                }}
              >
                <DataGrid
                  rows={dataTable}
                  columns={columns}
                  initialState={{ pagination: { paginationModel } }}
                  pageSizeOptions={[5, 10]}
                  sx={{
                    border: 0,
                    width: '100%', // 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>
        </div>
      </div>
    </div>
  )
}

export default Noteclasse