import AuthCheckBox from '../../components/common/input/AuthCheckBox';
import CheckBox from '../../components/common/input/CheckBox';
import { Title, FormWrapper, BtnWrapper, TableStyle, ButtonClose, ModalText } from '../../styles/Components';
import Button from '../../components/common/button/Button';
import { useLocation, useNavigate } from 'react-router-dom';
import { useEffect, useState } from 'react';
import { GroupDetailViewList, GroupModify } from '../../apis';
import Modal from '../../components/common/modal/Modal';

import { authList } from '../../store/authList';
import { useRecoilValue } from 'recoil';
import AuthModal from '../../components/common/modal/AuthModal';
import { authType } from '../../assets/data';

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

	const id = location.pathname.split('/')[3];
	const token = sessionStorage.getItem('token');
	const [dataList, setDataList] = useState([]);
	const [selectedRow, setSelectedRow] = useState({ group1: [], group2: [], group3: [], group4: [] });

	const [cancelModalClose, setCancelModalClose] = useState('hidden');
	const [saveModalClose, setSaveModalClose] = useState('hidden');
	const [confirmModalClose, setConfirmModalClose] = useState('hidden');
	const [confirmText, setConfirmText] = useState('');
	const [authRow, setAuthRow] = useState([]);

	const AdminViewList = ['2', '3', '4'];
	const AuthSettingList = ['7', '8'];
	const UserViewList = ['12', '35'];
	const BoardList = ['17', '18'];
	const WhiteList = ['20', '21', '28'];
	const MailList = ['23', '29'];
	const ReportList = ['25', '31'];
	const UserBlockList = ['27', '30']; //DB상 report가 31이고 blocklist가 30인데 추후 테스트 필요해보인다
	const ItemList = ['33', '34'];
	const EventList = ['37', '38'];
	const CaliumRequest = ['40'];
	const LandAuctionList = ['41', '42', '43'];

	useEffect(() => {
		fetchData();
	}, []);

	useEffect(() => {
		selectedRow && setAuthRow(selectedRow);
	}, [selectedRow]);

	const AdminView = authRow.group1 && authRow.group1.filter(data => AdminViewList.includes(data)).length > 0;
	const AuthSettingView = authRow.group1 && authRow.group1.filter(data => AuthSettingList.includes(data)).length > 0;
	const CaliumRequestView = authRow.group1 && authRow.group1.filter(data => CaliumRequest.includes(data)).length > 0;
	const UserView = authRow.group3 && authRow.group3.filter(data => UserViewList.includes(data)).length > 0;
	const BoardView = authRow.group4 && authRow.group4.filter(data => BoardList.includes(data)).length > 0;
	const WhiteView = authRow.group4 && authRow.group4.filter(data => WhiteList.includes(data)).length > 0;
	const MailView = authRow.group4 && authRow.group4.filter(data => MailList.includes(data)).length > 0;
	const ReportView = authRow.group4 && authRow.group4.filter(data => ReportList.includes(data)).length > 0;
	const BlockView = authRow.group4 && authRow.group4.filter(data => UserBlockList.includes(data)).length > 0;
	const ItemView = authRow.group4 && authRow.group4.filter(data => ItemList.includes(data)).length > 0;
	const EventView = authRow.group4 && authRow.group4.filter(data => EventList.includes(data)).length > 0;
	const LandAuctionView = authRow.group4 && authRow.group4.filter(data => LandAuctionList.includes(data)).length > 0;

	const fetchData = async () => {
		setDataList(await GroupDetailViewList(token, id));
	};

	useEffect(() => {
		const Group1List = dataList.auth_list && dataList.auth_list.filter(data => data.id >= 1 && data.id <= 8
			|| (data.id >= authType.caliumRequestRead && data.id <= authType.caliumRequestUpdate)).map(group => String(group.id));
		const Group2List = dataList.auth_list && dataList.auth_list.filter(data => data.id >= 9 && data.id <= 10).map(group => String(group.id));
		const Group3List = dataList.auth_list && dataList.auth_list.filter(data => (data.id >= 11 && data.id <= 15)
			|| data.id === 35).map(group => String(group.id));
		const Group4List = dataList.auth_list && dataList.auth_list.filter(data => (data.id >= 16 && data.id <= 34)
			|| (data.id >= 36 && data.id <= 38)
			|| (data.id >= authType.landAuctionRead && data.id <= authType.landAuctionDelete) ).map(group => String(group.id));

		setSelectedRow({ group1: Group1List, group2: Group2List, group3: Group3List, group4: Group4List });
	}, [dataList]);

	// 전체 선택 구현
	const handlGroupSelect = order => {
		let list = [];
		const groupAllCheck = document.getElementById('group' + order);
		const groupData = document.getElementsByName('group' + order);

		if (groupAllCheck.checked === true) {
			// console.log(groupData.length);
			for (let i = 0; i < groupData.length; i++) {
				const data = document.getElementsByName('group' + order)[i];
				data.checked = true;
				list.push(data.id);
			}
		} else if (groupAllCheck.checked === false) {
			for (let i = 0; i < groupData.length; i++) {
				const data = document.getElementsByName('group' + order)[i];
				data.checked = false;
				list = [];
			}
		}

		setSelectedRow({ ...selectedRow, ['group' + order]: list });
	};

	const handleSelectedAuthSave = () => {
		let strArr1 = Object.values(selectedRow[`group1`]);
		let strArr2 = Object.values(selectedRow[`group2`]);
		let strArr3 = Object.values(selectedRow[`group3`]);
		let strArr4 = Object.values(selectedRow[`group4`]);

		let resultList = [];

		const newArr = [...strArr1, ...strArr2, ...strArr3, ...strArr4];

		newArr.map(data => resultList.push({ auth_id: data }));
		
		GroupModify(token, id, resultList);

		handleSaveModalClose();
		handleConfirmeModalClose();
	};

	const handleExistedId = (id, name) => {
		return selectedRow[name] && selectedRow[name].includes(String(id));
	};

	// 취소 모달
	const handleCancelModalClose = () => {
		if (cancelModalClose === 'hidden') {
			setCancelModalClose('view');
		} else {
			setCancelModalClose('hidden');
			setConfirmText('취소가');
		}
	};

	// 저장 모달
	const handleSaveModalClose = () => {
		if (saveModalClose === 'hidden') {
			setSaveModalClose('view');
		} else {
			setSaveModalClose('hidden');
			setConfirmText('저장이');
		}
	};

	//  확인 모달창
	const handleConfirmeModalClose = () => {
		if (confirmModalClose === 'hidden') {
			setConfirmModalClose('view');
		} else {
			setConfirmModalClose('hidden');
			navigate('/usermanage/authsetting');
			window.location.reload();
		}
	};

	const handleCountSelectedRow = (name, count) => {
		switch (name) {
			case 'group1':
				return selectedRow.group1 && selectedRow.group1.filter(data => data >= 1 && data <= 8).length > 0;
			case 'group2':
				return selectedRow.group2 && selectedRow.group2.filter(data => data >= 9 && data <= 10).length > 0;
			case 'group3':
				return selectedRow.group3 && selectedRow.group3.filter(data => (data >= 11 && data <= 15)).length > 0;
			case 'group4':
				return selectedRow.group4 && selectedRow.group4.filter(data => (data >= 16 && data <= 38) || (data >= 41 && data <= 43)).length > 0;
			default:
		}
	};

	function killEvent(e) {
		e.stopPropagation();
		e.preventDefault();
	}

	// 체크박스 선택 리스트
	const handleSelectAuthCheckBox = e => {
		let list = selectedRow[e.target.name];

		if (e.target.checked) {
			list.push(e.target.id);

			if (AdminViewList.includes(e.target.id)) list.includes('1') || list.push('1');
			else if (AuthSettingList.includes(e.target.id)) list.includes('6') || list.push('6');
			else if (UserViewList.includes(e.target.id)) list.includes('11') || list.push('11');
			else if (BoardList.includes(e.target.id)) list.includes('16') || list.push('16');
			else if (WhiteList.includes(e.target.id)) list.includes('19') || list.push('19');
			else if (MailList.includes(e.target.id)) list.includes('22') || list.push('22');
			else if (ReportList.includes(e.target.id)) list.includes('24') || list.push('24');
			else if (UserBlockList.includes(e.target.id)) list.includes('26') || list.push('26');
			else if (ItemList.includes(e.target.id)) list.includes('32') || list.push('32');
			else if (EventList.includes(e.target.id)) list.includes('36') || list.push('36');
			else if (CaliumRequest.includes(e.target.id)) list.includes('39') || list.push('39');
			else if (CaliumRequest.includes(e.target.id)) list.includes('41') || list.push('41');

			setSelectedRow({ ...selectedRow, [e.target.name]: list });
		} else {
			const filterList = list.filter(data => e.target.id !== data);
			setSelectedRow({ ...selectedRow, [e.target.name]: filterList });
		}
	};

	return (
		<>
			{userInfo.auth_list && !userInfo.auth_list.some(auth => auth.id === authType.authoritySettingUpdate) ? (
				<AuthModal />
			) : (
				<>
					<Title>권한 설정</Title>
					<FormWrapper $flow="column">
						<TableStyle>
							<caption></caption>
							<thead>
								<tr>
									<th width="40"></th>
									<th></th>
									<th>메뉴</th>
									<th>조회</th>
									<th>승인</th>
									<th>등록 / 수정</th>
									<th>삭제</th>
								</tr>
							</thead>
							<tbody>
							<tr>
								<td rowSpan="4">
									<AuthCheckBox id="group1" handleCheck={() => handlGroupSelect(1)}
												  checked={handleCountSelectedRow('group1', 8)} />
								</td>
								<td rowSpan="4">운영자 관리</td>
								<td>운영자 조회</td>
								<td>
									<AuthCheckBox id="1" name="group1"
												  checked={handleExistedId(authType.adminSearchRead, 'group1') || AdminView}
												  setData={handleSelectAuthCheckBox} disabled={AdminView} />
								</td>
								<td>
									<AuthCheckBox id="2" name="group1"
												  checked={handleExistedId(authType.adminSearchConfirm, 'group1')}
												  setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<AuthCheckBox id="3" name="group1"
												  checked={handleExistedId(authType.adminSearchUpdate, 'group1')}
												  setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<AuthCheckBox id="4" name="group1"
												  checked={handleExistedId(authType.adminSearchDelete, 'group1')}
												  setData={handleSelectAuthCheckBox} />
								</td>
							</tr>
							<tr>
								<td>사용 이력 조회</td>
								<td>
									<AuthCheckBox id="5" name="group1"
												  checked={handleExistedId(authType.adminLogSearchRead, 'group1')}
												  setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
							</tr>
							<tr>
								<td>권한 설정</td>
								<td>
									<AuthCheckBox id="6" name="group1"
												  checked={handleExistedId(authType.authoritySettingRead, 'group1') || AuthSettingView}
												  disabled={AuthSettingView} setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
								<td>
									<AuthCheckBox id="7" name="group1"
												  checked={handleExistedId(authType.authoritySettingUpdate, 'group1')}
												  setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<AuthCheckBox id="8" name="group1"
												  checked={handleExistedId(authType.authoritySettingDelete, 'group1')}
												  setData={handleSelectAuthCheckBox} />
								</td>
							</tr>
							<tr>
								<td>칼리움 요청</td>
								<td>
									<AuthCheckBox id="39" name="group1"
												  checked={handleExistedId(authType.caliumRequestRead, 'group1') || CaliumRequestView}
												  disabled={CaliumRequestView} setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
								<td>
									<AuthCheckBox id="40" name="group1"
												  checked={handleExistedId(authType.caliumRequestUpdate, 'group1')}
												  setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
							</tr>
							<tr className="table-line">
								<td rowSpan="2">
									<AuthCheckBox id="group2" handleCheck={() => handlGroupSelect(2)}
												  checked={handleCountSelectedRow('group2', 2)} />
								</td>
								<td rowSpan="2">지표 관리</td>
								<td>유저 지표</td>
								<td>
									<AuthCheckBox id="9" name="group2"
												  checked={handleExistedId(authType.userIndicatorsRead, 'group2')}
												  setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
							</tr>
							<tr>
								<td>경제 지표</td>
								<td>
									<AuthCheckBox id="10" name="group2"
												  checked={handleExistedId(authType.economicIndicatorsRead, 'group2')}
												  setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
							</tr>
							<tr className="table-line">
								<td rowSpan="4">
									<AuthCheckBox id="group3" handleCheck={() => handlGroupSelect(3)}
												  checked={handleCountSelectedRow('group3', 5)} />
								</td>
								<td rowSpan="4">운영 정보 관리</td>
								<td>유저 조회</td>
								<td>
									<AuthCheckBox id="11" name="group3"
												  checked={handleExistedId(authType.userSearchRead, 'group3') || UserView}
												  disabled={UserView} setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
								<td>
									<AuthCheckBox id="12" name="group3"
												  checked={handleExistedId(authType.userSearchUpdate, 'group3')}
												  setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<AuthCheckBox id="35" name="group3"
												  checked={handleExistedId(authType.userSearchDelete, 'group3')}
												  setData={handleSelectAuthCheckBox} />
								</td>
							</tr>
							<tr>
								<td>컨텐츠 조회</td>
								<td>
									<AuthCheckBox id="13" name="group3"
												  checked={handleExistedId(authType.contentSearchRead, 'group3')}
												  setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
							</tr>
							<tr>
								<td>게임 로그 조회</td>
								<td>
									<AuthCheckBox id="14" name="group3"
												  checked={handleExistedId(authType.gameLogRead, 'group3')}
												  setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
							</tr>
							<tr>
								<td>크립토 조회</td>
								<td>
									<AuthCheckBox id="15" name="group3"
												  checked={handleExistedId(authType.cryptoRead, 'group3')}
												  setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
							</tr>
							<tr className="table-line">
								<td rowSpan="8">
									<AuthCheckBox id="group4" handleCheck={() => handlGroupSelect(4)}
												  checked={handleCountSelectedRow('group4', 25)} />
								</td>
								<td rowSpan="8">운영 서비스 관리</td>
								<td>인게임 메시지</td>
								<td>
									<AuthCheckBox id="16" name="group4"
												  checked={handleExistedId(authType.inGameRead, 'group4') || BoardView}
												  disabled={BoardView} setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
								<td>
									<AuthCheckBox id="17" name="group4"
												  checked={handleExistedId(authType.inGameUpdate, 'group4')}
												  setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<AuthCheckBox id="18" name="group4"
												  checked={handleExistedId(authType.inGameDelete, 'group4')}
												  setData={handleSelectAuthCheckBox} />
								</td>
							</tr>
							<tr>
								<td>화이트리스트</td>
								<td>
									<AuthCheckBox id="19" name="group4"
												  checked={handleExistedId(authType.whiteListRead, 'group4') || WhiteView}
												  disabled={WhiteView} setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<AuthCheckBox id="20" name="group4"
												  checked={handleExistedId(authType.whiteListConfirm, 'group4')}
												  setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<AuthCheckBox id="21" name="group4"
												  checked={handleExistedId(authType.whiteListUpdate, 'group4')}
												  setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<AuthCheckBox id="28" name="group4"
												  checked={handleExistedId(authType.whiteListDelete, 'group4')}
												  setData={handleSelectAuthCheckBox} />
								</td>
							</tr>
							<tr>
								<td>우편</td>
								<td>
									<AuthCheckBox id="22" name="group4"
												  checked={handleExistedId(authType.mailRead, 'group4') || MailView}
												  disabled={MailView} setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
								<td>
									<AuthCheckBox id="23" name="group4"
												  checked={handleExistedId(authType.mailUpdate, 'group4')}
												  setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<AuthCheckBox id="29" name="group4"
												  checked={handleExistedId(authType.mailDelete, 'group4')}
												  setData={handleSelectAuthCheckBox} />
								</td>
							</tr>
							<tr>
								<td>이용자 제재</td>
								<td>
									<AuthCheckBox id="24" name="group4"
												  checked={handleExistedId(authType.blackListRead, 'group4') || ReportView}
												  disabled={ReportView} setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
								<td>
									<AuthCheckBox id="25" name="group4"
												  checked={handleExistedId(authType.blackListUpdate, 'group4')}
												  setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<AuthCheckBox id="30" name="group4"
												  checked={handleExistedId(authType.blackListDelete, 'group4')}
												  setData={handleSelectAuthCheckBox} />
								</td>
							</tr>
							<tr>
								<td>신고내역</td>
								<td>
									<AuthCheckBox id="26" name="group4"
												  checked={handleExistedId(authType.reportRead, 'group4') || BlockView}
												  disabled={BlockView} setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
								<td>
									<AuthCheckBox id="27" name="group4"
												  checked={handleExistedId(authType.reportUpdate, 'group4')}
												  setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<AuthCheckBox id="31" name="group4"
												  checked={handleExistedId(authType.reportDelete, 'group4')}
												  setData={handleSelectAuthCheckBox} />
								</td>
							</tr>
							<tr>
								<td>아이템 복구 및 삭제</td>
								<td>
									<AuthCheckBox id="32" name="group4"
												  checked={handleExistedId(authType.itemRead, 'group4') || ItemView}
												  disabled={ItemView} setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
								<td>
									<AuthCheckBox id="33" name="group4"
												  checked={handleExistedId(authType.itemUpdate, 'group4')}
												  setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<AuthCheckBox id="34" name="group4"
												  checked={handleExistedId(authType.itemDelete, 'group4')}
												  setData={handleSelectAuthCheckBox} />
								</td>
							</tr>
							<tr>
								<td>보상 이벤트 관리</td>
								<td>
									<AuthCheckBox id="36" name="group4"
												  checked={handleExistedId(authType.eventRead, 'group4')}
												  disabled={EventView} setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
								<td>
									<AuthCheckBox id="37" name="group4"
												  checked={handleExistedId(authType.eventUpdate, 'group4')}
												  setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<AuthCheckBox id="38" name="group4"
												  checked={handleExistedId(authType.eventDelete, 'group4')}
												  setData={handleSelectAuthCheckBox} />
								</td>
							</tr>
							<tr>
								<td>랜드 경매 관리</td>
								<td>
									<AuthCheckBox id="41" name="group4"
												  checked={handleExistedId(authType.landAuctionRead, 'group4')}
												  disabled={LandAuctionView} setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<CheckBox disabled={true} />
								</td>
								<td>
									<AuthCheckBox id="42" name="group4"
												  checked={handleExistedId(authType.landAuctionUpdate, 'group4')}
												  setData={handleSelectAuthCheckBox} />
								</td>
								<td>
									<AuthCheckBox id="43" name="group4"
												  checked={handleExistedId(authType.landAuctionDelete, 'group4')}
												  setData={handleSelectAuthCheckBox} />
								</td>
							</tr>
							</tbody>
						</TableStyle>
						<BtnWrapper $justify="flex-end" $gap="5px">
							<Button
								theme="line"
								handleClick={e => {
									e.preventDefault();
									handleCancelModalClose();
								}}
								text="취소"
							/>
							<Button
								type="submit"
								theme="primary"
								text="저장"
								handleClick={e => {
									e.preventDefault();
									handleSaveModalClose();
								}}
							/>
						</BtnWrapper>
					</FormWrapper>

					{/* 취소 모달 */}
					<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={cancelModalClose}>
						<BtnWrapper $justify="flex-end">
							<ButtonClose onClick={handleCancelModalClose} />
						</BtnWrapper>
						<ModalText $align="center">
							취소하시겠습니까?
							<br />
							취소 시 변경된 값은 초기화됩니다.
						</ModalText>
						<BtnWrapper $gap="10px">
							<Button text="취소" theme="line" size="large" width="100%" handleClick={handleCancelModalClose} />
							<Button
								text="확인"
								theme="primary"
								type="submit"
								size="large"
								width="100%"
								handleClick={() => {
									handleCancelModalClose();
									handleConfirmeModalClose();
								}}
							/>
						</BtnWrapper>
					</Modal>
					{/* 저장 모달 */}
					<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={saveModalClose}>
						<BtnWrapper $justify="flex-end">
							<ButtonClose onClick={handleSaveModalClose} />
						</BtnWrapper>
						<ModalText $align="center">저장하시겠습니까? </ModalText>
						<BtnWrapper $gap="10px">
							<Button text="취소" theme="line" size="large" width="100%" handleClick={handleSaveModalClose} />
							<Button text="확인" theme="primary" type="submit" size="large" width="100%" handleClick={handleSelectedAuthSave} />
						</BtnWrapper>
					</Modal>
					{/* 확인 모달 */}
					<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={confirmModalClose}>
						<BtnWrapper $justify="flex-end">
							<ButtonClose onClick={handleConfirmeModalClose} />
						</BtnWrapper>
						<ModalText $align="center">{confirmText} 완료되었습니다.</ModalText>
						<BtnWrapper $gap="10px">
							<Button text="확인" theme="primary" type="submit" size="large" width="100%" handleClick={handleConfirmeModalClose} />
						</BtnWrapper>
					</Modal>
				</>
			)}
		</>
	);
};

export default AuthSettingUpdate;
