import React, { useEffect, useState } from 'react'
import { Button } from '@mui/material'
import { createTheme, ThemeProvider } from '@mui/material/styles'
import { IoEyeSharp } from 'react-icons/io5'
import { frFR } from '@mui/x-data-grid/locales'
import { Tooltip } from 'react-tooltip'
import Paper from '@mui/material/Paper'
import { DataGrid, GridToolbar } from '@mui/x-data-grid'
import classe from '../assets/AllStyleComponents.module.css'
import classeHome from '../assets/Home.module.css'
import { Link } from 'react-router-dom'

const Notes = () => {
  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 }

  const columns = [
    { field: 'niveau', headerName: 'Niveau', width: 170 },
    { field: 'annee_scolaire', headerName: 'Année Univesitaire', width: 160 },
    // { field:'moyenne', headerName:'Moyenne de classe', width:160},
    {
      field: 'action',
      headerName: 'Action',
      flex: 1,
      renderCell: (params) => (
        <div style={{ display: 'flex', gap: '10px' }}>
          <Link to={`/noteclass/${params.row.niveau}/${params.row.annee_scolaire}`}>
            <Button color="warning" variant="contained" className={`update${params.value}`}>
              <IoEyeSharp style={{ fontSize: '20px', color: 'white' }} />
            </Button>
            <Tooltip
              anchorSelect={`.update${params.value}`}
              style={{ fontSize: '13px', zIndex: 22 }}
              place="bottom-end"
            >
              Voir tous les etudiants dans ce niveau
            </Tooltip>
          </Link>
        </div>
      )
    }
  ]

  /**
   * hook for dispplaying note
   */
  const [blockNotes, SetBlockNotes] = useState([])

  useEffect(() => {
    window.notes.getblockNote().then((response) => {
      SetBlockNotes(response)
    })
  }, [])

  const calculMoyenneDeClasse = (L1, annee) => {
    let data = blockNotes.allData
    let note = 0
    let someId = []
    let total = 0
    let totalEtudiant = []
    let id = []
    let totalCredit = 0

    if (data != undefined) {
      for (let index = 0; index < data.length; index++) {
        for (let j = 0; j < data[index].length; j++) {
          if (data[index][j].niveau == L1 && data[index][j].annee_scolaire == annee) {
            totalEtudiant.push(data[index][j])
          }
        }
      }
    }

    for (let index = 0; index < totalEtudiant.length; index++) {
      someId.push(totalEtudiant[index].etudiant_id)
      id = [...new Set(someId)]
      note += totalEtudiant[index].note * totalEtudiant[index].credit
      totalCredit += totalEtudiant[index].credit
    }
    total = note / totalCredit

    return total.toFixed(2)
  }

  let dataRow
  if (blockNotes.response) {
    dataRow = blockNotes.response.map((note, index) => ({
      id: index,
      niveau: note.etudiant_niveau,
      moyenne: calculMoyenneDeClasse(note.etudiant_niveau, note.annee_scolaire),
      annee_scolaire: note.annee_scolaire,
      action: note.niveau
    }))
  } else {
    dataRow = []
  }

  return (
    <div className={classe.mainHome}>
      <div className={classeHome.header}>
        <div className={classe.h1style}>
          <div className={classeHome.blockTitle}>
            <h1>Notes</h1>
          </div>
        </div>
      </div>

      {/* display the data-grid students */}
      <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={dataRow}
                  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 Notes
