import React, { useEffect, useState } from 'react'
import classe from '../assets/AllStyleComponents.module.css'
import { Bar } from 'react-chartjs-2'
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend
} from 'chart.js'
import classeHome from '../assets/Home.module.css'
import dclass from '../assets/Dashboard.module.css'
import dayjs from 'dayjs'
import MenuItem from '@mui/material/MenuItem'
import FormControl from '@mui/material/FormControl'
import Select from '@mui/material/Select'
import InputLabel from '@mui/material/InputLabel'

ChartJS.register(CategoryScale, LinearScale, BarElement, Title, Tooltip, Legend)

const Home = () => {
  const [etudiants, setEtudiants] = useState([])
  const [niveau, setNiveau] = useState([])
  const [annee_scolaire, setAnnee_scolaire] = useState([])
  const [originalEtudiants, setOriginalEtudiants] = useState([])
  // Get the current year
  const currentYear = dayjs().year()

  useEffect(() => {
    // Fetch data and update state
    window.etudiants.getDataToDashboards().then((response) => {
      setEtudiants(response.etudiants)
      setOriginalEtudiants(response.etudiants)
      setNiveau(response.niveau)
      setAnnee_scolaire(response.anne_scolaire)
    })
  }, [])

  // filter all data

  // ordre des colones de filtre
  const desiredOrder = ['L1', 'L2', 'L3', 'M1', 'M2', 'D1', 'D2', 'D3']
  let allNiveau = niveau.map((item) => item.nom)
  allNiveau.sort((a, b) => desiredOrder.indexOf(a) - desiredOrder.indexOf(b))

  const studentGrades = {}

  // Loop through allNiveau and set the number of students for each key
  allNiveau.forEach((niveauNom) => {
    // Filter etudiants based on the matching niveau
    const studentCount = etudiants.filter((etudiant) => etudiant.niveau === niveauNom).length

    // Assign the student count as the value for the corresponding key in studentGrades
    studentGrades[niveauNom] = studentCount
  })
  const studentCounts = Object.values(studentGrades)

  // Find the maximum value using Math.max
  const maxStudentCount = Math.max(...studentCounts)

  const FilterAnneeScolaire = (e) => {
    let annee_scolaire = e.target.value
    const filteredEtudiants = originalEtudiants.filter(
      (etudiant) => etudiant.annee_scolaire === annee_scolaire
    )
    setEtudiants(filteredEtudiants)
    if (annee_scolaire == 'general') {
      setEtudiants(originalEtudiants)
    }
  }
  // end filter all data

  // Calculate the number of classes
  const numberOfClasses = Object.keys(studentGrades).length

  // Data for the Bar chart
  const data = {
    labels: Object.keys(studentGrades), // Class levels
    datasets: [
      {
        label: 'Nombre des étudiants',
        data: Object.values(studentGrades), // Student counts
        backgroundColor: [
          '#FF6384',
          '#36A2EB',
          '#FFCE56',
          '#4BC0C0',
          '#9966FF',
          '#FF9F40',
          '#C9CBCF',
          '#00A36C'
        ], // Colors for each bar
        borderColor: [
          '#FF6384',
          '#36A2EB',
          '#FFCE56',
          '#4BC0C0',
          '#9966FF',
          '#FF9F40',
          '#C9CBCF',
          '#00A36C'
        ],
        borderWidth: 1
      }
    ]
  }

  // Chart options
  const options = {
    responsive: true,
    plugins: {
      legend: {
        position: 'top'
      },
      title: {
        display: true,
        text: `Nombre des niveau (Total : ${numberOfClasses})`
      }
    },
    scales: {
      y: {
        beginAtZero: true,
        max: maxStudentCount // Set max value for the Y axis
      }
    }
  }

  return (
    <div className={classe.mainHome}>
      <div className={classeHome.header}>
        <div className={classe.h1style}>
          <div className={classeHome.blockTitle}>
            <h1>Dashboard</h1>
            <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: '15px', textTransform: 'capitalize' }}
                color="warning"
              >
                Année Univesitaire
              </InputLabel>
              <Select
                labelId="demo-select-small-label"
                id="demo-select-small"
                label="Année Univesitaire"
                color="warning"
                defaultValue={'general'}
                onChange={FilterAnneeScolaire}
                sx={{
                  background: 'white',
                  textTransform: 'capitalize',
                  display: 'flex',
                  alignItems: 'center', // Align icon and text vertically
                  '& .MuiSelect-icon': {
                    marginLeft: 'auto' // Keep the dropdown arrow to the right
                  }
                }}
              >
                <MenuItem value="general" selected>
                  <em>Géneral</em>
                </MenuItem>
                {annee_scolaire.map((niveau) => (
                  <MenuItem value={niveau.annee_scolaire} key={niveau.annee_scolaire}>
                    {niveau.annee_scolaire}
                  </MenuItem>
                ))}
              </Select>
            </FormControl>
          </div>
        </div>
      </div>
      {/* display each bars */}
      <div className={dclass.display}>
        <Bar data={data} options={options} />
      </div>
    </div>
  )
}

export default Home
