import { useLocation, useNavigate } from 'react-router-dom';
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useRecoilValue } from 'recoil';
import { useTranslation } from 'react-i18next';

import { authList } from '../../store/authList';
import { authType, modalTypes } from '../../assets/data';
import { menuConfig } from '../../assets/data/menuConfig';
import { Title, FormWrapper, BtnWrapper, TableStyle } from '../../styles/Components';
import { GroupDetailViewList, GroupModify } from '../../apis';
import Button from '../../components/common/button/Button';
import AuthModal from '../../components/common/modal/AuthModal';
import DynamicModal from '../../components/common/modal/DynamicModal';
import { AuthGroupRows } from '../../components/UserManage';

const AuthSettingUpdate = () => {
	const location = useLocation();
	const navigate = useNavigate();
	const userInfo = useRecoilValue(authList);
	const { t } = useTranslation();

	const id = location.pathname.split('/')[3];
	const [msg, setMsg] = useState('');

	const {
		authGroups,
		selectedPermissions,
		modalState,
		setSelectedPermissions,
		setModalState
	} = useAuthSetting(id);

	if (!userInfo.auth_list?.some(auth => auth.id === authType.authoritySettingUpdate)) {
		return <AuthModal />;
	}

	const handlePermissionChange = (groupId, permissionId) => {
		setSelectedPermissions(prev => {
			const newPermissions = { ...prev };

			if (permissionId === 'all') {
				const group = authGroups.find(g => g.id === groupId);
				const allPermissions = group.items.flatMap(item =>
					Object.values(item.permissions)
				);

				newPermissions[groupId] = allPermissions;
			} else if (permissionId === 'none') {
				newPermissions[groupId] = [];
			} else {
				const currentGroupPermissions = newPermissions[groupId] || [];
				if (currentGroupPermissions.includes(Number(permissionId))) {
					newPermissions[groupId] = currentGroupPermissions.filter(id =>
						id !== Number(permissionId)
					);
				} else {
					newPermissions[groupId] = [...currentGroupPermissions, Number(permissionId)];
				}
			}

			return newPermissions;
		});
	};

	const handleModalView = (type) => {
		setModalState((prevState) => ({
			...prevState,
			[`${type}Modal`]: 'view',
		}));
	}

	const handleModalClose = (type) => {
		setModalState((prevState) => ({
			...prevState,
			[`${type}Modal`]: 'hidden',
		}));
	}

	const handleSubmit = async (type, param = null) => {
		switch (type) {
			case "cancelConfirm":
				setMsg(t('CANCEL_COMPLETED'));

				handleModalClose('cancelConfirm');
				handleModalView('complete');
				break;
			case "registConfirm":
				const token = sessionStorage.getItem('token');
				const resultList = Object.values(selectedPermissions)
					.flat()
					.map(permissionId => ({ auth_id: permissionId }));

				await GroupModify(token, id, resultList);

				setMsg(t('SAVE_COMPLETED'));

				handleModalClose('registConfirm');
				handleModalView('complete');
				break;
			case "complete":
				handleModalClose('complete');
				setMsg('');
				navigate('/usermanage/authsetting');
				// window.location.reload();
				break;
		}
	}

	return (
		<>
			{userInfo.auth_list && !userInfo.auth_list.some(auth => auth.id === authType.authoritySettingUpdate) ? (
				<AuthModal />
			) : (
				<>
					<Title>권한 설정</Title>
					<FormWrapper $flow="column">
						<TableStyle>
							<thead>
							<tr>
								<th width="40"></th>
								<th></th>
								<th>메뉴</th>
								<th>조회</th>
								<th>승인</th>
								<th>등록/수정</th>
								<th>삭제</th>
							</tr>
							</thead>
							<tbody>
							{authGroups.map((group) => (
								<AuthGroupRows
									key={group.id}
									group={group}
									selectedPermissions={selectedPermissions[group.id] || []}
									onPermissionChange={handlePermissionChange}
								/>
							))}
							</tbody>
						</TableStyle>
						<BtnWrapper $justify="flex-end" $gap="5px">
							<Button
								theme="line"
								handleClick={() => handleModalView('cancelConfirm')}
								text="취소"
							/>
							<Button
								theme="primary"
								handleClick={() => handleModalView('registConfirm')}
								text="저장"
							/>
						</BtnWrapper>
					</FormWrapper>

					<DynamicModal
						modalType={modalTypes.confirmOkCancel}
						view={modalState.cancelConfirmModal}
						modalText={t('CANCEL_CONFIRM')}
						handleSubmit={() => handleSubmit('cancelConfirm')}
						handleCancel={() => handleModalClose('cancelConfirm')}
					/>

					<DynamicModal
						modalType={modalTypes.confirmOkCancel}
						view={modalState.registConfirmModal}
						modalText={t('SAVE_CONFIRM')}
						handleSubmit={() => handleSubmit('registConfirm')}
						handleCancel={() => handleModalClose('registConfirm')}
					/>

					<DynamicModal
						modalType={modalTypes.completed}
						view={modalState.completeModal}
						modalText={msg}
						handleSubmit={() => handleSubmit('complete')}
					/>

				</>
			)}
		</>
	);
};

const useAuthSetting = (initialId) => {
	const token = sessionStorage.getItem('token');
	const [selectedPermissions, setSelectedPermissions] = useState({});
	const [modalState, setModalState] = useState({
		cancelConfirmModal: 'hidden',
		registConfirmModal: 'hidden',
		completeModal: 'hidden',
	});

	// menuConfig를 기반으로 권한 그룹 구조화
	const authGroups = useMemo(() => {
		return Object.entries(menuConfig).map(([key, section]) => ({
			id: key,
			title: section.title,
			items: Object.entries(section.items).map(([itemKey, item]) => ({
				id: itemKey,
				title: item.title,
				permissions: item.permissions
			}))
		}));
	}, []);

	// 권한 ID로 그룹과 아이템 찾기
	const findPermissionLocation = useCallback((permissionId) => {
		for (const [groupKey, group] of Object.entries(menuConfig)) {
			for (const [itemKey, item] of Object.entries(group.items)) {
				if (Object.values(item.permissions).includes(permissionId)) {
					return { groupKey, itemKey };
				}
			}
		}
		return null;
	}, []);

	// API 데이터를 menuConfig 구조에 맞게 변환
	const formatPermissionsData = useCallback((apiData) => {
		return apiData.auth_list.reduce((acc, auth) => {
			const location = findPermissionLocation(auth.id);
			if (location) {
				if (!acc[location.groupKey]) {
					acc[location.groupKey] = [];
				}
				acc[location.groupKey].push(auth.id);
			}
			return acc;
		}, {});
	}, [findPermissionLocation]);

	useEffect(() => {
		const fetchInitialData = async () => {
			const data = await GroupDetailViewList(token, initialId);
			const formattedPermissions = formatPermissionsData(data);
			setSelectedPermissions(formattedPermissions);
		};

		fetchInitialData();
	}, [initialId, formatPermissionsData]);

	return {
		authGroups,
		selectedPermissions,
		modalState,
		setSelectedPermissions,
		setModalState
	};
};

export default AuthSettingUpdate;
