import { NavLink, useNavigate } from 'react-router-dom';
import arrowIcon from '../../../assets/img/icon/icon-tab.png';
import styled from 'styled-components';
import { useRecoilValue } from 'recoil';
import { authList } from '../../../store/authList';
import Modal from '../modal/Modal';
import { BtnWrapper, ButtonClose, ModalText } from '../../../styles/Components';
import { useEffect, useState } from 'react';
import Button from '../button/Button';
import { useLocation } from 'react-router-dom';
import { AuthInfo } from '../../../apis';
import { authType } from '../../../assets/data';
import { menuConfig } from '../../../assets/data/menuConfig';
import { getMenuConfig } from '../../../utils';

const Navi = () => {
	const token = sessionStorage.getItem('token');
	const userInfo = useRecoilValue(authList);
	const menu = getMenuConfig(userInfo);

	const [modalClose, setModalClose] = useState('hidden');
	const [logoutModalClose, setLogoutModalClose] = useState('hidden');
	const location = useLocation();
	const navigate = useNavigate();

	const handleToken = async () => {
		const tokenStatus = await AuthInfo(token);

		tokenStatus.message === '잘못된 타입의 토큰입니다.' && setLogoutModalClose('view');
	};

	useEffect(() => {
		handleToken();
	}, [token]);

	const handleTopMenu = e => {
		e.preventDefault();
		e.target.classList.toggle('active');
	};

	const handleLink = e => {
		let topActive = document.querySelectorAll('nav .active');
		let currentTopMenu = e.target.closest('ul').previousSibling;
		for (let i = 0; i < topActive.length; i++) {
			if (topActive[i] !== currentTopMenu) {
				topActive[i].classList.remove('active');
			}
		}

		handleToken();
	};

	// 등록 완료 모달
	const handleModalClose = () => {
		if (modalClose === 'hidden') {
			setModalClose('view');
		} else {
			setModalClose('hidden');
		}
	};

	// 로그아웃 안내 모달
	const handleConfirmClose = () => {
		if (logoutModalClose === 'hidden') {
			setLogoutModalClose('view');
		} else {
			setLogoutModalClose('hidden');
			sessionStorage.removeItem('token');

			navigate('/');
		}
	};

	// const menu = [
	// 	{
	// 		title: '운영자 관리',
	// 		link: '/usermanage',
	// 		access: userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === authType.adminSearchRead || auth.id === authType.adminLogSearchRead || auth.id === authType.authoritySettingRead || auth.id === authType.caliumRequestRead),
	// 		submenu: [
	// 			{ title: '운영자 조회', link: '/usermanage/adminview', id: authType.adminSearchRead },
	// 			{ title: '사용 이력 조회', link: '/usermanage/logview', id: authType.adminLogSearchRead },
	// 			{ title: '권한 설정', link: '/usermanage/authsetting', id: authType.authoritySettingRead },
	// 			{ title: '칼리움 요청', link: '/usermanage/caliumrequest', id: authType.caliumRequestRead },
	// 		],
	// 	},
	// 	{
	// 		title: '지표 관리',
	// 		link: '/indexmanage',
	// 		access: userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === authType.userIndicatorsRead || auth.id === authType.economicIndicatorsRead),
	// 		submenu: [
	// 			{ title: '유저 지표', link: '/indexmanage/userindex', id: authType.userIndicatorsRead },
	// 			{ title: '경제 지표', link: '/indexmanage/economicindex', id: authType.economicIndicatorsRead },
	// 		],
	// 	},
	// 	{
	// 		title: '운영 정보 관리',
	// 		link: '/datamanage',
	// 		access: userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === authType.userSearchRead || auth.id === authType.contentSearchRead || auth.id === authType.gameLogRead || auth.id === authType.cryptoRead),
	// 		submenu: [
	// 			{ title: '유저 조회', link: '/datamanage/userview', id: authType.userIndicatorsRead },
	// 			{ title: '컨텐츠 조회', link: '/datamanage/contentsview', id: authType.contentSearchRead },
	// 			{ title: '게임 로그 조회', link: '/datamanage/gamelogview', id: authType.gameLogRead },
	// 			{ title: '크립토 조회', link: '/datamanage/cryptview', id: authType.cryptoRead },
	// 		],
	// 	},
	// 	{
	// 		title: '운영 서비스 관리',
	// 		link: '/servicemanage',
	// 		access: userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === authType.inGameRead || auth.id === authType.whiteListRead || auth.id === authType.mailRead
	// 			|| auth.id === authType.blackListRead || auth.id === authType.reportRead || auth.id === authType.itemRead || auth.id === authType.eventRead ),
	// 		submenu: [
	// 			{ title: '인게임 메시지', link: '/servicemanage/board', id: authType.inGameRead },
	// 			// { title: '화이트리스트', link: '/servicemanage/whitelist', id: authType.whiteListRead },
	// 			{ title: '우편', link: '/servicemanage/mail', id: authType.mailRead },
	// 			{ title: '이용자 제재', link: '/servicemanage/userblock', id: authType.blackListRead },
	// 			{ title: '신고내역', link: '/servicemanage/reportlist', id: authType.reportRead },
	// 			// { title: '아이템 복구 및 삭제', link: '/servicemanage/items', id: authType.itemRead },
	// 			{ title: '보상 이벤트 관리', link: '/servicemanage/event', id: authType.eventRead },
	// 		],
	// 	},
	// ];

	return (
		<>
			<nav>
				<ul>
					{menu.map((item, idx) => {
						return (
							<li key={idx}>
								{item.access && (
									<TopMenu to={item.link} onClick={handleTopMenu}>
										{item.title}
									</TopMenu>
								)}
								<SubMenu>
									{item.submenu &&
										item.submenu.map((submenu, idx) => {
											return (
												<SubMenuItem key={idx} $isclickable={userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === submenu.id) ? 'true' : 'false'}>
													<NavLink
														to={userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === submenu.id) ? submenu.link : location.pathname}
														onClick={e => {
															userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === submenu.id) ? handleLink(e) : handleModalClose();
														}}>
														{submenu.title}
													</NavLink>
												</SubMenuItem>
											);
										})}
								</SubMenu>
							</li>
						);
					})}
				</ul>
			</nav>
			{/* 접근 불가 모달 */}
			<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={modalClose}>
				<BtnWrapper $justify="flex-end">
					<ButtonClose onClick={handleModalClose} />
				</BtnWrapper>
				<ModalText $align="center">
					해당 메뉴에 대한 조회 권한이 없습니다.
					<br />
					권한 등급을 변경 후 다시 이용해주세요.
				</ModalText>
				<BtnWrapper $gap="10px">
					<Button text="확인" theme="primary" type="submit" size="large" width="100%" handleClick={handleModalClose} />
				</BtnWrapper>
			</Modal>

			{/* 로그아웃 안내 모달 */}
			<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={logoutModalClose}>
				<BtnWrapper $justify="flex-end">
					<ButtonClose onClick={handleConfirmClose} />
				</BtnWrapper>
				<ModalText $align="center">로그아웃 되었습니다.</ModalText>
				<BtnWrapper $gap="10px">
					<Button text="확인" theme="primary" type="submit" size="large" width="100%" handleClick={handleConfirmClose} />
				</BtnWrapper>
			</Modal>
		</>
	);
};

export default Navi;

const TopMenu = styled(NavLink)`
	padding: 16px 30px;
	width: 100%;
	text-align: left;
	border-bottom: 1px solid #888;
	position: relative;
	color: #fff;

	&:before {
		content: '';
		display: block;
		width: 12px;
		height: 12px;
		position: absolute;
		right: 30px;
		top: 50%;
		transform: translate(0, -50%);
		background: url('${arrowIcon}') -12px 0 no-repeat;
	}
	&:hover,
	&.active {
		background: #444;
	}
	&.active ~ ul {
		display: block;
	}
	&.active:before {
		background: url('${arrowIcon}') 0 0 no-repeat;
	}
`;

const SubMenu = styled.ul`
	display: none;
`;

const SubMenuItem = styled.li`
	background: #eee;
	border-bottom: 1px solid #ccc;
	color: #2c2c2c;
	a {
		width: 100%;
		padding: 16px 30px;
		color: ${props => (props.$isclickable === 'false' ? '#818181' : '#2c2c2c')};
		text-align: left;
		&:hover,
		&.active {
			color: ${props => (props.$isclickable === 'false' ? '#818181' : '#2c2c2c')};
			font-weight: ${props => (props.$isclickable === 'false' ? 400 : 600)};
		}
	}
`;

const BackGround = styled.div`
	background: #eee2;
	width: 100%;
	height: 100%;
	z-index: 100;
`;
