import React from "react";
import { useNavigate } from "react-router";
import { useSelector } from "react-redux";

import SidebarItem from "./SidebarItem.jsx";
import logo from "../../resources/files/images/logo.png";
import MenuIcon from "@mui/icons-material/Menu";
import CloseIcon from '@mui/icons-material/Close';

export default function Sidebar({items}) {
  //전역 변수 저장 객체
  const state = useSelector((state) => {return state});

  const [menuToggle, setMenuToggle] = React.useState(false);

  const onClickshow=()=>{
    setMenuToggle(!menuToggle)
  }
  const navigate = useNavigate();
  //로그아웃
  const logout = () => {
    fetch("/user/logout.json", {
      method: "POST",
      headers: {
        'Content-Type': 'application/json; charset=UTF-8'
      },
      /* body: JSON.stringify({}), */
    }).then((response) => response.json()).then((data) => {
      console.log("로그아웃 결과 : ", data);
      if (data == true) {
        navigate('/Main');
      } else {
        alert('로그아웃 실패, 관리자에게 문의바랍니다.');
      }
    }).catch((error) => {
      console.log('logout() /user/logout.json error : ', error);
    });
  };
  const [iconIndex, setIconIndex] = React.useState(0);
  const icons = [<MenuIcon sx={{ fontSize: 40, }}/>, <CloseIcon sx={{ fontSize: 40, }}/>];
  const handleClick = () => {
    setIconIndex((iconIndex + 1) % icons.length);   
  };
  return (
 <>
      <nav className={menuToggle? "nav on" : "nav"}>
        <div className="menuicon"  onClick={() => {onClickshow(); handleClick();}}>
          {icons[iconIndex]} 
        </div>
        <h1 className="logo"><img src={logo} alt="" /></h1>
        <div className="flex-align-column" style={{ marginTop: `3rem` }}>
          <ul >
            {items.map((item, index) => (
              <SidebarItem key={index} item={item} />
            ))}
          </ul>
        </div>
        <div className="bottom-section flex-center" style={{width: '100%'}}>
            {state.loginUser['authority'] == 'ROLE_ADMIN'
              || state.loginUser['authority'] == 'ROLE_GOVERNMENT'
              || state.loginUser['authority'] == 'ROLE_AGENCY' ? 
              <div className="info-id" >
                <span onClick={() => {
                  navigate("/Join");
                }}>계정추가</span>
              </div>
            : null}
            <div className="logout" onClick={logout}><span>로그아웃</span></div>
          </div>
      </nav>
        
 </>
  );
}
