import { useState, useEffect, Fragment, useCallback } from 'react';

import { SearchBar } from '../../components/common/SearchBar';
import CheckBox from '../../components/common/input/CheckBox';
import Modal from '../../components/common/modal/Modal';
import { Title, FormWrapper, TableInfo, ListTitle, ListOption, TableStyle, BtnWrapper, ButtonClose, ModalText } from '../../styles/Components';
import Button from '../../components/common/button/Button';
import { WhiteListSearchBar } from '../../components/ServiceManage';

import { styled } from 'styled-components';
import { WhiteListData, WhiteListDelete, WhiteListRegist, WhiteListAllow, WhiteListExport } from '../../apis/WhiteList';
import { authList } from '../../store/authList';
import { useRecoilValue } from 'recoil';
import { useNavigate } from 'react-router-dom';
import AuthModal from '../../components/common/modal/AuthModal';
import { authType } from '../../assets/data';

const WhiteList = () => {
	const navigate = useNavigate();

	const token = sessionStorage.getItem('token');
	const userInfo = useRecoilValue(authList);
	const [resultData, setResultData] = useState({ guid: '' });
	const [doubleSubmitFlag, setDoubleSubmitFlag] = useState(false);

	const [selectedRow, setSelectedRow] = useState([]);
	const [selectedId, setSelectedId] = useState([]);
	const [dataList, setDataList] = useState([]);
	const [deleteModalClose, setDeleteModalClose] = useState('hidden');
	const [confirmModalClose, setConfirmModalClose] = useState('hidden');
	const [deleteUserClose, setDeleteUserClose] = useState('hidden');
	const [completeModalClose, setCompleteModalClose] = useState('hidden');
	const [registModalClose, setRegistModalClose] = useState('hidden');
	const [allowModalClose, setAllowModalClose] = useState('hidden');
	const [confirmAllowClose, setConfirmAllowClose] = useState('hidden');
	const [userAllowClose, setUserAllowClose] = useState('hidden');
	const [isNullValue, setIsNullValue] = useState(false);
	const [confirmText, setConfirmText] = useState('');

	const [approveAble, setApproveAble] = useState(false);

	const fetchData = async () => {
		setDataList(await WhiteListData(token));
	};

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

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

	// 전체 선택
	const handleAllSelect = () => {
		const checkAll = document.getElementById('check-all');
		let list = [];

		if (checkAll.checked === true) {
			dataList.map((data, index) => {
				document.getElementsByName('select')[index].checked = true;
				list.push(String(data.id));
			});
		} else if (checkAll.checked === false) {
			for (let i = 0; i < dataList.length; i++) {
				dataList.map((data, index) => (document.getElementsByName('select')[index].checked = false));
				list = [];
			}
		}

		setSelectedRow(list);
	};

	// 일부 선택
	const handleSelectCheckBox = e => {
		let list = [...selectedRow];

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

			setSelectedRow(list);
		} else {
			const filterList = list.filter(data => e.target.id !== data);
			setSelectedRow(filterList);
		}
	};

	// 선택 승인 유효성 검사
	const approveCheck = e => {
		let approveList = [];

		dataList && dataList.map(data => data.status === 'PERMITTED' && approveList.push(data.id));

		return approveList;
	};

	const handleApproveCheck = () => {
		let list = [];
		let approveList = approveCheck();

		selectedRow.map(data => list.push(Number(data)));
		setApproveAble(approveList.filter(row => list.includes(row)).length === 0);
	};

	// 선택 삭제 모달창
	const handleDeleteModalClose = () => {
		if (selectedRow.length !== 0) {
			if (deleteModalClose === 'hidden') {
				setDeleteModalClose('view');
			} else {
				setDeleteModalClose('hidden');
			}
		}
	};

	// 삭제 확인 모달창
	const handleConfirmModalClose = () => {
		if (confirmModalClose === 'hidden') {
			setConfirmModalClose('view');
		} else {
			setConfirmModalClose('hidden');
			window.location.reload();
		}
	};

	// 선택 삭제 버튼
	const handleSelectedDelete = () => {
		let list = [];

		selectedRow.map(data =>
			list.push({
				id: data,
			}),
		);

		WhiteListDelete(token, list);
		handleDeleteModalClose();
		handleConfirmModalClose();
	};

	// 개별 삭제 모달
	const handleUserDeleteModalClose = dataValue => {
		if (deleteUserClose === 'hidden') {
			setDeleteUserClose('view');
		} else {
			setDeleteUserClose('hidden');
		}

		if (dataValue) {
			setSelectedId(dataValue.id);
		}
	};

	// 개별 삭제 버튼
	const handleDelete = () => {
		let list = [];

		list.push({ id: selectedId });
		WhiteListDelete(token, list);
		handleUserDeleteModalClose();
		handleConfirmModalClose();
		setSelectedId([]);
	};

	// 등록 확인 모달
	const handleRegistModalClose = () => {
		if (resultData.guid.length === 0) {
			setIsNullValue(true);
		} else if (registModalClose === 'hidden') {
			setRegistModalClose('view');
			setIsNullValue(false);
		} else {
			setRegistModalClose('hidden');
		}
	};
	// console.log(resultData.guid.length)

	// 등록 완료 모달
	const handleCompleteModalClose = () => {
		if (completeModalClose === 'hidden') {
			setCompleteModalClose('view');
		} else {
			setCompleteModalClose('hidden');
			window.location.reload();
		}
	};

	// 화이트 리스트 등록하기
	const handleSubmit = async () => {
		const message = await WhiteListRegist(token, resultData);

		if (message.data.data.message === '등록 하였습니다.') setConfirmText('등록이 완료되었습니다.');
		else if (message.data.data.message === 'admindb_exit_error') setConfirmText('해당 유저가 이미 등록되어있습니다. \n 확인 후 다시 이용해주세요.');
		else if (message.data.data.message === '중복된 유저 정보가 있습니다.') setConfirmText('파일 내 중복된 유저 정보가 있습니다. \n 파일을 다시 확인 후 이용해주세요.');
		else setConfirmText(message.data.data.message);

		handleRegistModalClose();
		handleCompleteModalClose();
	};

	// 선택 승인 모달창
	const handleAllowModalClose = () => {
		if (selectedRow.length !== 0) {
			if (allowModalClose === 'hidden') {
				setAllowModalClose('view');
			} else {
				setAllowModalClose('hidden');
			}
		}
	};

	// 승인 완료 모달창
	const handleConfirmAllowClose = () => {
		if (confirmAllowClose === 'hidden') {
			setConfirmAllowClose('view');
		} else {
			setConfirmModalClose('hidden');
			window.location.reload();
		}
	};

	// 일괄 승인
	const handleAllow = () => {
		let list = [];

		selectedRow.map(data =>
			list.push({
				id: data,
			}),
		);

		WhiteListAllow(token, list);
		handleAllowModalClose();
		handleConfirmAllowClose();
	};

	// 개별 승인
	const handleUserAllowModalClose = dataValue => {
		if (userAllowClose === 'hidden') {
			setUserAllowClose('view');
		} else {
			setUserAllowClose('hidden');
		}

		if (dataValue) {
			setSelectedId(dataValue.id);
		}
	};

	// 개별 승인 버튼
	const handleUserAllow = () => {
		let list = [];

		list.push({ id: selectedId });
		WhiteListAllow(token, list);
		handleUserAllowModalClose();
		handleConfirmAllowClose();
		setSelectedId([]);
	};

	// 엑셀 다운로드
	const handleXlsxExport = () => {
		const fileName = 'Caliverse_whitelist.xlsx';
		WhiteListExport(token, fileName);
	};

	const handleCountSelectedRow = () => {
		return dataList && document.querySelectorAll('input[name="select"]:checked').length === dataList.length;
	};

	return (
		<>
			{userInfo.auth_list && !userInfo.auth_list.some(auth => auth.id === authType.whiteListRead) ? (
				<AuthModal />
			) : (
				<>
					<Title>화이트리스트 등록/수정</Title>
					{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === 21) && (
						<FormWrapper>
							<WhiteListSearchBar handleRegistModalClose={handleRegistModalClose} isNullValue={isNullValue} resultData={resultData} setResultData={setResultData} />
						</FormWrapper>
					)}
					<TableInfo>
						<ListTitle>화이트리스트 명단</ListTitle>
						<ListOption>
							<Button theme="line" type="file" text="엑셀 다운로드" handleClick={handleXlsxExport} />
							{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === 28) && (
								<Button theme={selectedRow.length === 0 ? 'disable' : 'line'} type="submit" text="선택 삭제" handleClick={handleDeleteModalClose} />
							)}
							{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === 20) && (
								<Button
									theme={selectedRow.length === 0 || !approveAble ? 'disable' : 'line'}
									type="submit"
									text="선택 승인"
									errorMessage={!approveAble}
									handleClick={handleAllowModalClose}
								/>
							)}
						</ListOption>
					</TableInfo>
					<TableWrapper>
						<TableStyle>
							<caption></caption>
							<thead>
								<tr>
									<th width="40">
										<CheckBox id="check-all" handleCheck={handleAllSelect} checked={handleCountSelectedRow()} />
									</th>
									<th width="80">번호</th>
									<th width="40%">GUID</th>
									<th width="25%">닉네임</th>
									<th width="25%">등록자(이메일주소)</th>
									<th width="100">승인</th>
									{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === 28) && <th width="100">삭제</th>}
								</tr>
							</thead>
							<tbody>
								{dataList &&
									dataList.map(data => (
										<Fragment key={data.guid}>
											<tr>
												<td>
													<CheckBox name={'select'} id={data.id} setData={e => handleSelectCheckBox(e)} handleCheck={handleApproveCheck} />
												</td>
												<td>{data.row_num}</td>
												<td>{data.guid}</td>
												<td>{data.nickname}</td>
												<td>{data.create_by}</td>
												{/* 승인 상태 */}
												{data.status !== 'REJECT' ? (
													<td>승인</td>
												) : userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === 20) ? (
													<td>
														<Button theme="line" text="승인" id={data.id} handleClick={() => handleUserAllowModalClose(data)} />
													</td>
												) : (
													<td>대기 중</td>
												)}
												{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === 28) && (
													<td>
														<Button theme="line" text="삭제" id={data.id} handleClick={() => handleUserDeleteModalClose(data)} />
													</td>
												)}
											</tr>
										</Fragment>
									))}
							</tbody>
						</TableStyle>
					</TableWrapper>

					{/* 선택삭제 모달 */}
					<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={deleteModalClose}>
						<BtnWrapper $justify="flex-end">
							<ButtonClose onClick={handleDeleteModalClose} />
						</BtnWrapper>
						<ModalText $align="center">
							선택된 대상을 화이트리스트 유저에서
							<br />
							삭제하시겠습니까?
						</ModalText>
						<BtnWrapper $gap="10px">
							<Button text="취소" theme="line" size="large" width="100%" handleClick={handleDeleteModalClose} />
							<Button text="확인" theme="primary" type="submit" size="large" width="100%" handleClick={handleSelectedDelete} />
						</BtnWrapper>
					</Modal>

					{/* 등록 모달 */}
					<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={registModalClose}>
						<BtnWrapper $="flex-end">
							<ButtonClose onClick={handleRegistModalClose} />
						</BtnWrapper>
						<ModalText $align="center">
							화이트리스트 명단에
							<br />
							등록하시겠습니까?
						</ModalText>
						<BtnWrapper $gap="10px">
							<Button text="취소" theme="line" size="large" width="100%" handleClick={handleRegistModalClose} />
							<Button
								text="확인"
								theme="primary"
								type="submit"
								size="large"
								width="100%"
								handleClick={() => {
									doubleSubmitFlag || handleSubmit();
									setDoubleSubmitFlag(true);
								}}
							/>
						</BtnWrapper>
					</Modal>

					{/* 개별 삭제 모달 */}
					<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={deleteUserClose}>
						<BtnWrapper $justify="flex-end">
							<ButtonClose onClick={handleUserDeleteModalClose} />
						</BtnWrapper>
						<ModalText $align="center">
							화이트리스트 유저를
							<br />
							삭제하시겠습니까?
						</ModalText>
						<BtnWrapper $gap="10px">
							<Button text="취소" theme="line" size="large" width="100%" handleClick={handleUserDeleteModalClose} />
							<Button text="확인" theme="primary" type="submit" size="large" width="100%" handleClick={handleDelete} />
						</BtnWrapper>
					</Modal>

					{/* 승인 모달 */}
					<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={allowModalClose}>
						<BtnWrapper $justify="flex-end">
							<ButtonClose onClick={handleAllowModalClose} />
						</BtnWrapper>
						<ModalText $align="center">
							선택된 대상을 화이트리스트 유저로
							<br />
							승인하시겠습니까?
						</ModalText>
						<BtnWrapper $gap="10px">
							<Button text="취소" theme="line" size="large" width="100%" handleClick={handleAllowModalClose} />
							<Button text="확인" theme="primary" type="submit" size="large" width="100%" handleClick={handleAllow} />
						</BtnWrapper>
					</Modal>

					{/* 개별 승인 모달 */}
					<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={userAllowClose}>
						<BtnWrapper $justify="flex-end">
							<ButtonClose onClick={handleUserAllowModalClose} />
						</BtnWrapper>
						<ModalText $align="center">
							선택된 대상을 화이트리스트 유저로
							<br />
							승인하시겠습니까?
						</ModalText>
						<BtnWrapper $gap="10px">
							<Button text="취소" theme="line" size="large" width="100%" handleClick={handleUserAllowModalClose} />
							<Button text="확인" theme="primary" type="submit" size="large" width="100%" handleClick={handleUserAllow} />
						</BtnWrapper>
					</Modal>

					{/* 완료 모달 */}

					{/* 등록 완료 모달 */}
					<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={completeModalClose}>
						<BtnWrapper $justify="flex-end">
							<ButtonClose onClick={handleCompleteModalClose} />
						</BtnWrapper>
						<ModalText $align="center">{confirmText}</ModalText>
						<BtnWrapper $gap="10px">
							<Button text="확인" theme="primary" type="submit" size="large" width="100%" handleClick={handleCompleteModalClose} />
						</BtnWrapper>
					</Modal>

					{/* 승인 완료 모달 */}
					<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={confirmAllowClose}>
						<BtnWrapper $justify="flex-end">
							<ButtonClose onClick={handleConfirmAllowClose} />
						</BtnWrapper>
						<ModalText $align="center">승인이 완료되었습니다.</ModalText>
						<BtnWrapper $gap="10px">
							<Button text="확인" theme="primary" type="submit" size="large" width="100%" handleClick={handleConfirmAllowClose} />
						</BtnWrapper>
					</Modal>

					{/* 삭제 확인 모달 */}
					<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={confirmModalClose}>
						<BtnWrapper $justify="flex-end">
							<ButtonClose onClick={handleConfirmModalClose} />
						</BtnWrapper>
						<ModalText $align="center">삭제가 완료되었습니다.</ModalText>
						<BtnWrapper $gap="10px">
							<Button text="확인" theme="primary" type="submit" size="large" width="100%" handleClick={handleConfirmModalClose} />
						</BtnWrapper>
					</Modal>
				</>
			)}
		</>
	);
};

export default WhiteList;

const TableWrapper = styled.div`
	height: calc(100vh - 383px);
	border-top: 1px solid #000;
	overflow: auto;
	&::-webkit-scrollbar {
		width: 4px;
	}
	&::-webkit-scrollbar-thumb {
		background: #666666;
	}
	&::-webkit-scrollbar-track {
		background: #d9d9d9;
	}
	thead {
		th {
			position: sticky;
			top: 0;
			z-index: 10;
		}
	}
`;

const StatusRed = styled.td`
	color: #d60000;
`;
