import React, { useState, useEffect } from 'react'
import classe from '../assets/Sidenav.module.css'
import { RiDashboardHorizontalFill } from 'react-icons/ri'
import { PiStudentFill } from 'react-icons/pi'
import { IoMdHelpCircleOutline } from 'react-icons/io'
import { CgNotes } from 'react-icons/cg'
import { FaUserCircle, FaBook, FaUserCog } from 'react-icons/fa'
import { Link } from 'react-router-dom'
import { useLocation } from 'react-router-dom'
import { Tooltip } from 'react-tooltip'
import { LuLogOut } from 'react-icons/lu'
import { GiUpgrade } from 'react-icons/gi'
import Menu from '@mui/material/Menu'
import MenuItem from '@mui/material/MenuItem'
import { useAuthContext } from '../contexts/AuthContext'
import { MdAdminPanelSettings, MdRule } from 'react-icons/md'
import { BsCalendar2Date } from 'react-icons/bs'
import { SiVitest } from 'react-icons/si'
import { GrManual } from 'react-icons/gr'
import { FaClipboardList } from 'react-icons/fa6'

const Sidenav = () => {
  const [anchorEl, setAnchorEl] = useState(null)
  const [userRole, setUserRole] = useState(null)
  const open = Boolean(anchorEl)
  const { setToken } = useAuthContext()
  const { user } = useAuthContext()

  // // Récupération du rôle utilisateur au montage du composant
  // useEffect(() => {
  //   const fetchUserRole = async () => {
  //     try {
  //       // Supposant que vous avez une méthode getUser dans votre contexte ou API
  //       const user = await window.allUser?.users(); // ou votre méthode d'API
  //       console.log('Résultat de getAllUsers:', user)
  //       setUserRole(user?.roles?.toLowerCase()) // Normaliser en minuscule
  //     } catch (error) {
  //       console.error('Erreur lors de la récupération du rôle utilisateur:', error)
  //       setUserRole(null)
  //     }
  //   }

  //   fetchUserRole()
  // }, [])

  const handleClick = (event) => {
    setAnchorEl(event.currentTarget)
  }

  const handleClose = () => {
    setAnchorEl(null)
  }

  // don't touch it, i don't know why but the active button stop workin without this
  const location = useLocation()

  const logout = () => {
    localStorage.removeItem('ACCESS_TOKEN')
    setToken(null)
  }

  // Fonction pour vérifier si l'utilisateur est admin
const isAdmin = () => {
  console.log('Rôle de l’utilisateur:', user?.roles)
  return user?.roles?.toLowerCase() === 'admin'
}
  return (
    <nav className={classe.navbar}>
      <style>
        {`
        .custom-tooltip {
          font-size: 15px;
          border: solid 1px white !important;
          border-radius: 4px;
        }
      `}
      </style>
      <ul className={classe.liste1}>
        <li>
          <Link
            to={'/'}
            className={classe.nav_link}
            style={{
              outline: 'none',
              borderBottom: window.location.hash == '#/' ? '2px solid white' : 'none'
            }}
          >
            <RiDashboardHorizontalFill className="dashboard" style={{ outline: 'none' }} />
            <Tooltip anchorSelect=".dashboard" className="custom-tooltip" place="top">
              Dashboard
            </Tooltip>
          </Link>
        </li>
        <li>
          <Link
            to={'/student'}
            className={classe.nav_link}
            style={{
              outline: 'none',
              borderBottom: window.location.hash == '#/student' ? '2px solid white' : 'none'
            }}
          >
            <PiStudentFill className="student" style={{ outline: 'none' }} />
            <Tooltip anchorSelect=".student" className="custom-tooltip" place="top">
              Etudiants
            </Tooltip>
          </Link>
        </li>
        
        {/* Navigation Notes - Visible uniquement pour les admins */}
        {isAdmin() && (
          <li>
            <Link
              to={'/notes'}
              className={classe.nav_link}
              style={{
                outline: 'none',
                borderBottom: window.location.hash == '#/notes' ? '2px solid white' : 'none'
              }}
            >
              <CgNotes className="notes" style={{ outline: 'none' }} />
              <Tooltip anchorSelect=".notes" className="custom-tooltip" place="top">
                Notes
              </Tooltip>
            </Link>
          </li>
        )}

        <li>
          <Link
            to={'/mention'}
            className={classe.nav_link}
            style={{
              outline: 'none',
              borderBottom: window.location.hash == '#/mention' ? '2px solid white' : 'none'
            }}
          >
            <FaClipboardList className="mention" style={{ outline: 'none' }} />
            <Tooltip anchorSelect=".mention" className="custom-tooltip" place="top">
              Mentions
            </Tooltip>
          </Link>
        </li>
        <li>
          <Link
            to={'/matiere'}
            className={classe.nav_link}
            style={{
              outline: 'none',
              borderBottom: window.location.hash == '#/matiere' ? '2px solid white' : 'none'
            }}
          >
            <FaBook className="matiere" style={{ outline: 'none' }} />
            <Tooltip anchorSelect=".matiere" className="custom-tooltip" place="top">
              Matières
            </Tooltip>
          </Link>
        </li>
        <li>
          <Link
            to={'/niveau'}
            className={classe.nav_link}
            style={{
              outline: 'none',
              borderBottom: window.location.hash == '#/niveau' ? '2px solid white' : 'none'
            }}
          >
            <GiUpgrade className="niveau" style={{ outline: 'none' }} />
            <Tooltip anchorSelect=".niveau" className="custom-tooltip" place="top">
              Niveau
            </Tooltip>
          </Link>
        </li>
        <li>
          <Link
            to={'/anneescolaire'}
            className={classe.nav_link}
            style={{
              outline: 'none',
              borderBottom: window.location.hash == '#/niveau' ? '2px solid white' : 'none'
            }}
          >
            <BsCalendar2Date className="anneescolaire" style={{ outline: 'none' }} />
            <Tooltip anchorSelect=".anneescolaire" className="custom-tooltip" place="top">
              Année Univesitaire
            </Tooltip>
          </Link>
        </li>
        <li>
          <Link
            to={'/parcours'}
            className={classe.nav_link}
            style={{
              outline: 'none',
              borderBottom: window.location.hash == '#/parcours' ? '2px solid white' : 'none'
            }}
          >
            <MdRule className="rules" style={{ outline: 'none' }} />
            <Tooltip anchorSelect=".rules" className="custom-tooltip" place="top">
              Parcours
            </Tooltip>
          </Link>
        </li>
        <li>
          <Link
            to={'/apropos'}
            className={classe.nav_link}
            style={{
              outline: 'none',
              borderBottom: window.location.hash == '#/apropos' ? '2px solid white' : 'none'
            }}
          >
            <IoMdHelpCircleOutline className="Apropos" style={{ outline: 'none' }} />
            <Tooltip anchorSelect=".Apropos" className="custom-tooltip" place="top">
              A propos
            </Tooltip>
          </Link>
        </li>
      </ul>
      <ul className={classe.liste2}>
        <li>
          <Link
            id="basic-button"
            aria-controls={open ? 'basic-menu' : undefined}
            aria-haspopup="true"
            aria-expanded={open ? 'true' : undefined}
            onClick={handleClick}
            style={{
              outline: 'none',
              borderBottom:
                window.location.hash == '#/admin' || window.location.hash == '#/para'
                  ? '2px solid white'
                  : 'none'
            }}
            to={'#'}
            className={classe.nav_link}
          >
            <FaUserCircle className="admin" style={{ outline: 'none' }} />
            <Tooltip anchorSelect=".admin" place="top" className="custom-tooltip">
              Admin
            </Tooltip>
          </Link>

          <Menu
            id="basic-menu"
            anchorEl={anchorEl}
            open={open}
            onClose={handleClose}
            MenuListProps={{
              'aria-labelledby': 'basic-button'
            }}
          >
            <MenuItem>
              <Link
                to="/systemenote"
                style={{ color: 'black', textDecoration: 'none' }}
                onClick={handleClose}
              >
                <CgNotes /> Système des notes
              </Link>
            </MenuItem>
            <MenuItem>
              <Link
                to="/admin"
                style={{ color: 'black', textDecoration: 'none' }}
                onClick={handleClose}
              >
                <MdAdminPanelSettings /> Admin
              </Link>
            </MenuItem>
            <MenuItem>
              <Link
                to="/para"
                style={{ color: 'black', textDecoration: 'none' }}
                onClick={handleClose}
              >
                <FaUserCog /> Paramètre
              </Link>
            </MenuItem>
          </Menu>
        </li>
        <li>
          <LuLogOut className="logout" style={{ outline: 'none' }} onClick={logout} />
          <Tooltip anchorSelect=".logout" className="custom-tooltip" place="top">
            Déconnexion
          </Tooltip>
        </li>
      </ul>
    </nav>
  )
}

export default Sidenav