import { NavLink, useNavigate, useLocation } from 'react-router-dom';
import { ConfigProvider, Menu, theme } from 'antd';
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 { AuthInfo } from '../../../apis';
import { getMenuConfig } from '../../../utils';
import { adminAuthLevel } from '../../../assets/data/types';

const Navi = () => {
	const token = sessionStorage.getItem('token');
	const userInfo = useRecoilValue(authList);
	const menuConfig = getMenuConfig(userInfo);
	const location = useLocation();
	const navigate = useNavigate();
	
	const [modalClose, setModalClose] = useState('hidden');
	const [logoutModalClose, setLogoutModalClose] = useState('hidden');
	const [openKeys, setOpenKeys] = useState([]);
	const [selectedKeys, setSelectedKeys] = useState([]);

	// 현재 경로에 따라 선택된 메뉴와 열린 서브메뉴 설정
	useEffect(() => {
		const path = location.pathname.split('/');
		if (path.length > 1) {
			// 첫 번째 경로(예: /usermanage)를 기반으로 openKeys 설정
			setOpenKeys([path[1]]);
			
			// 전체 경로(예: /usermanage/adminview)를 기반으로 selectedKeys 설정
			if (path.length > 2) {
				setSelectedKeys([`${path[1]}/${path[2]}`]);
			} else {
				setSelectedKeys([path[1]]);
			}
		}
	}, [location.pathname]);

	const handleToken = async () => {
		const tokenStatus = await AuthInfo(token);
		if (tokenStatus.message === '잘못된 타입의 토큰입니다.') {
			setLogoutModalClose('view');
		}
	};

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

	// 메뉴 아이템 클릭 핸들러
	const handleMenuClick = ({ key }) => {
		handleToken();
	};

	// 서브메뉴 열기/닫기 핸들러
	const handleOpenChange = (keys) => {
		setOpenKeys(keys);
	};

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

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

	const isClickable = (submenu) => {
		switch (userInfo.auth_level_type) {
			case adminAuthLevel.DEVELOPER:
			case adminAuthLevel.READER:
			case adminAuthLevel.MASTER:
				return true;
			default:
				return submenu.authLevel === adminAuthLevel.NONE && userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === submenu.id);
		}
	};

	const getMenuItems = () => {
		return menuConfig
			.filter(item => item.access)
			.map(item => ({
				key: item.link.substring(1),
				label: item.title,
				children: item.submenu.map(submenu => ({
					key: `${item.link.substring(1)}/${submenu.link.split('/').pop()}`,
					label: (
						<MenuItemLink 
							to={isClickable(submenu) ? submenu.link : location.pathname} 
							$isclickable={isClickable(submenu) ? 'true' : 'false'}
							onClick={(e) => {
								if (!isClickable(submenu)) {
									e.preventDefault();
									handleModalClose();
								}
							}}
						>
							{submenu.title}
						</MenuItemLink>
					),
					disabled: !isClickable(submenu)
				}))
			}));
	};

	return (
		<>
			<StyledNavWrapper>
				<ConfigProvider
					theme={{
						algorithm: theme.darkAlgorithm,
					}}
				>
					<StyledMenu
						theme="dark"
						mode="inline"
						openKeys={openKeys}
						selectedKeys={selectedKeys}
						onOpenChange={handleOpenChange}
						onClick={handleMenuClick}
						items={getMenuItems()}
						multiple={true}
					/>
				</ConfigProvider>
			</StyledNavWrapper>

			{/* 접근 불가 모달 */}
			<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 StyledNavWrapper = styled.div`
`;

const StyledMenu = styled(Menu)`
`;

const MenuItemLink = styled(NavLink)`
	
	&.active {
		font-weight: ${props => (props.$isclickable === 'false' ? 400 : 600)};
	}
`;