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

import CheckBox from '../../components/common/input/CheckBox';
import { Title, FormWrapper, SelectInput, BtnWrapper, TableInfo, ListCount, ListOption, TableStyle, State, ButtonClose, ModalText } from '../../styles/Components';
import Button from '../../components/common/button/Button';
import Pagination from '../../components/common/Pagination/Pagination';
import Modal from '../../components/common/modal/Modal';

import { AdminViewList, AdminViewGroupList, AdminLoginApprove, AdminDeleteUser, AdminChangeGroup, AdminChangePw } from '../../apis/Admin';
import AdminViewSearchBar from '../../components/UserManage/AdminViewSearchBar';
import { useNavigate } from 'react-router-dom';

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

function AdminView() {
	const token = sessionStorage.getItem('token');
	const userInfo = useRecoilValue(authList);
	const navigate = useNavigate();

	const [currentPage, setCurrentPage] = useState(1);

	const [dataList, setDataList] = useState([]);
	const [groupList, setGroupList] = useState([]);
	const [selectedRow, setSelectedRow] = useState([]);
	const [selectedGroup, setSelectedGroup] = useState([]);
	const [searchData, setSearchData] = useState({});
	const [selectedEmail, setSelectedEmail] = useState('');
	const [orderBy, setOrderBy] = useState('DESC');

	const [deleteModalClose, setDeleteModalClose] = useState('hidden');
	const [approveModalClose, setApproveModalClose] = useState('hidden');
	const [saveModalClose, setSaveModalClose] = useState('hidden');
	const [confirmModalClose, setConfirmModalClose] = useState('hidden');
	const [confirmText, setConfirmText] = useState('');
	const [singleConfirmText, setSingleConfirmText] = useState('');
	const [singleModalClose, setSingleModalClose] = useState('hidden');
	const [initialModalClose, setInitialModalClose] = useState('hidden');

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

	const [pageSize, setPageSize] = useState('50');

	// 그룹 권한 조회 후 전체 리스트 불러오기 && 페이징
	useEffect(() => {
		fetchGroupData();
		setSelectedRow([]);
	}, [currentPage]);

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

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

	// 선택 승인 모달
	const handleApproveModalClose = () => {
		if (selectedRow.length !== 0 && approveModalClose === 'hidden' && approveAble) {
			setApproveModalClose('view');
		} else {
			setApproveModalClose('hidden');
			setConfirmText('승인이');
		}
	};

	// 저장 모달
	const handleSaveModalClose = () => {
		if (selectedGroup.length !== 0 && saveModalClose === 'hidden') {
			setSaveModalClose('view');
		} else {
			setSaveModalClose('hidden');
			setConfirmText('저장이');
		}
	};

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

	// 단일 승인 or 반려 모달
	const handleSingleModalClose = () => {
		if (singleModalClose === 'hidden') {
			setSingleModalClose('view');
		} else {
			setSingleModalClose('hidden');
			window.location.reload();
		}
	};

	// 비밀번호 초기화 모달
	const handleInitialModalClose = () => {
		if (initialModalClose === 'hidden') {
			setInitialModalClose('view');
		} else {
			setInitialModalClose('hidden');
		}
	};

	// 리스트 조회
	const fetchData = async (searchType, searchKey, groupType, joinCheck, order, size) => {
		setDataList(await AdminViewList(token, searchType, searchKey, groupType, joinCheck, order ? order : orderBy, size ? size : pageSize, currentPage));
	};

	// 그룹 조회
	const fetchGroupData = async () => {
		setGroupList(await AdminViewGroupList(token));
		fetchData(searchData.searchOption, searchData.data, searchData.authorityOption, searchData.joinCheck, orderBy, pageSize);
	};

	// 검색 함수
	const handleSearch = (searchType, searchKey, groupType, joinCheck) => {
		fetchData(searchType, searchKey, groupType, joinCheck);
	};

	// 오름차순 내림차순
	const handleOrderBy = e => {
		const order = e.target.value;

		setOrderBy(order);
		fetchData(searchData.searchOption, searchData.data, searchData.authorityOption, searchData.joinCheck, order, pageSize);
	};

	// 페이징
	const handlePageSize = e => {
		const size = e.target.value;
		setPageSize(size);
		setCurrentPage(1);
		fetchData(searchData.searchOption, searchData.data, searchData.authorityOption, searchData.joinCheck, orderBy, size, 1);
	};

	// 사용자 승인
	const handleApprove = userEmail => {
		let list = [];

		list.push({
			email: userEmail,
			is_approve: 'APPROVE',
		});

		AdminLoginApprove(token, list);
	};

	// 사옹자 반려
	const handleReject = userEmail => {
		let list = [];

		list.push({
			email: userEmail,
			is_approve: 'REJECT',
		});

		AdminLoginApprove(token, 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 = () => {
		let list = [];
		dataList.list && dataList.list.map(data => data.status === 'ROLE_NOT_PERMITTED' && list.push(data.email));

		return list;
	};

	// 승인 버튼 validation
	const handleApproveCheck = () => {
		const list = approveCheck();
		setApproveAble(list.filter(row => selectedRow.includes(row)).length === selectedRow.length);
	};

	// 변경된 권한 등급 리스트
	const handleGroupGrade = e => {
		let list = [...selectedGroup];

		const filterList = list.filter(data => e.target.id !== data.email);
		filterList.push({ email: e.target.id, group_id: e.target.value });
		setSelectedGroup(filterList);
	};

	// 선택 승인 함수
	const handleSelectedApprove = () => {
		selectedRow.map(data => handleApprove(data));

		handleApproveModalClose();
		handleConfirmeModalClose();
	};

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

		selectedRow.map(data =>
			list.push({
				email: data,
			}),
		);
		AdminDeleteUser(token, list);

		handleDeleteModalClose();
		handleConfirmeModalClose();
	};

	// 단일 승인 함수
	const handleSingleApprove = data => {
		handleApprove(data);

		setSingleConfirmText('승인이 완료되었습니다.');
		handleSingleModalClose();
	};

	// 선택 반려 함수
	const handleSingleReject = data => {
		handleReject(data);

		setSingleConfirmText('승인이 반려되었습니다.');
		handleSingleModalClose();
	};

	// 수정된 권한 등급 저장 함수
	const handleSelectedGroupSave = () => {
		AdminChangeGroup(token, selectedGroup);

		handleSaveModalClose();
		handleConfirmeModalClose();
	};

	// 비밀번호 저장 함수
	const handleResetPw = data => {
		setSelectedEmail(data);

		handleInitialModalClose();
	};

	const handlePasswordInitialize = () => {
		AdminChangePw(token, { email: selectedEmail });

		// console.log(selectedEmail);

		setConfirmText('비밀번호 초기화가');
		handleInitialModalClose();
		handleConfirmeModalClose();
	};
	// 전체 선택 구현
	const handleAllSelect = () => {
		let list = [];
		if (document.getElementById('check-all').checked === true) {
			dataList.list.map((data, index) => {
				document.getElementsByName('select')[index].checked = true;
				list.push(data.email);
			});
		} else if (document.getElementById('check-all').checked === false) {
			for (let i = 0; i < dataList.list.length; i++) {
				dataList.list.map((data, index) => (document.getElementsByName('select')[index].checked = false));
				list = [];
			}
		}
		setSelectedRow(list);
	};

	const handleCountSelectedRow = () => {
		return currentPage > (dataList && dataList.total) / pageSize ? selectedRow.length === dataList.total % pageSize : selectedRow.length === Number(pageSize);
	};

	return (
		<>
			{userInfo.auth_list && !userInfo.auth_list.some(auth => auth.id === 1) ? (
				<AuthModal />
			) : (
				<>
					<Title>운영자 조회</Title>
					<FormWrapper action="" $flow="row">
						<AdminViewSearchBar handleSearch={handleSearch} groupList={groupList} setResultData={setSearchData} setCurrentPage={setCurrentPage} />
					</FormWrapper>

					<TableInfo>
						<ListCount>
							총 : {dataList && dataList.total} 건 / {dataList && dataList.total_all} 건
						</ListCount>
						<ListOption>
							<SelectInput className="input-select" onChange={e => handleOrderBy(e)}>
								<option value="DESC">내림차순</option>
								<option value="ASC">오름차순</option>
							</SelectInput>
							<SelectInput className="input-select" onChange={e => handlePageSize(e)}>
								<option value="50">50개</option>
								<option value="100">100개</option>
							</SelectInput>
							{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === 4) && (
								<Button theme={selectedRow.length === 0 ? 'disable' : 'line'} text="선택 삭제" handleClick={handleDeleteModalClose} />
							)}
							{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === 2) && (
								<Button theme={selectedRow.length === 0 || !approveAble ? 'disable' : 'line'} text="선택 승인" handleClick={handleApproveModalClose} />
							)}
							{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === 3) && <Button theme="primary" text="저장" handleClick={handleSaveModalClose} />}
						</ListOption>
					</TableInfo>
					<TableStyle>
						<caption></caption>
						<thead>
							<tr>
								<th width="40">
									<CheckBox id="check-all" handleCheck={handleAllSelect} checked={handleCountSelectedRow()} />
								</th>
								<th width="80">번호</th>
								<th width="200">이름</th>
								<th>ID (이메일 주소)</th>
								<th width="150">로그인 승인 상태</th>
								<th width="20%">권한 등급</th>
								{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === 3) && <th width="120">비밀번호 초기화</th>}
							</tr>
						</thead>
						<tbody>
							{dataList.list &&
								dataList.list.map(user => (
									<Fragment key={user.id}>
										<tr>
											<td>
												<CheckBox
													name={'select'}
													id={user.email}
													setData={e => {
														handleSelectCheckBox(e);
													}}
													handleCheck={handleApproveCheck}
												/>
											</td>
											<td>{user.row_num}</td>
											<td>{user.name}</td>
											<td>{user.email}</td>
											{user.status !== 'ROLE_NOT_PERMITTED' ? (
												user.status === 'PERMITTED' || user.status === 'INIT' ? (
													<td>
														<span>승인완료</span>
													</td>
												) : (
													<td>
														<State color="#d60000">신청 반려</State>
													</td>
												)
											) : userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === 2) ? (
												<td>
													<BtnWrapper $gap="5px" $justify="center">
														<Button theme="primary" text="승인" handleClick={() => handleSingleApprove(user.email)} />
														<Button theme="line" text="불가" handleClick={() => handleSingleReject(user.email)} />
													</BtnWrapper>
												</td>
											) : (
												<td>
													<State color="gray">승인 대기 중</State>
												</td>
											)}

											{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === 3) ? (
												<td>
													<SelectInput id={user.email} defaultValue={!user.group_id ? '선택' : user.group_id} onChange={e => handleGroupGrade(e)}>
														{user.group_id || (
															<option key={'선택'} value={'선택'} disabled>
																선택
															</option>
														)}

														{groupList &&
															groupList.map(group => (
																<option key={group.group_id} value={group.group_id}>
																	{group.group_nm}
																</option>
															))}
													</SelectInput>
												</td>
											) : (
												<td>
													<SelectInput id={user.email} defaultValue={user.group_id} disabled color="gray">
														{groupList &&
															groupList.map(group => (
																<option key={group.group_id} value={group.group_id}>
																	{group.group_nm}
																</option>
															))}
													</SelectInput>
												</td>
											)}

											{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === 3) && (
												<td>{(user.status === 'PERMITTED' || user.status === 'INIT') && <Button theme="reset" handleClick={() => handleResetPw(user.email)} />}</td>
											)}
										</tr>
									</Fragment>
								))}
						</tbody>
					</TableStyle>
					<Pagination postsPerPage={pageSize} totalPosts={dataList && dataList.total_all} setCurrentPage={setCurrentPage} currentPage={currentPage} pageLimit={10} />
					{/* 선택 삭제 모달 */}
					<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={approveModalClose}>
						<BtnWrapper $justify="flex-end">
							<ButtonClose onClick={handleApproveModalClose} />
						</BtnWrapper>
						<ModalText $align="center">
							선택된 운영자 로그인을
							<br />
							승인하시겠습니까?
						</ModalText>
						<BtnWrapper $gap="10px">
							<Button text="취소" theme="line" size="large" width="100%" handleClick={handleApproveModalClose} />
							<Button text="확인" theme="primary" type="submit" size="large" width="100%" handleClick={handleSelectedApprove} />
						</BtnWrapper>
					</Modal>
					{/* 저장 모달 */}
					<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={saveModalClose}>
						<BtnWrapper $justify="flex-end">
							<ButtonClose onClick={handleSaveModalClose} />
						</BtnWrapper>
						<ModalText $align="center">
							운영자 정보 수정사항을
							<br />
							저장하시겠습니까?
						</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={handleSelectedGroupSave} />
						</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>
					{/* 단일 승인 or 반려 모달 */}
					<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={singleModalClose}>
						<BtnWrapper $justify="flex-end">
							<ButtonClose onClick={handleSingleModalClose} />
						</BtnWrapper>
						<ModalText $align="center">{singleConfirmText}</ModalText>
						<BtnWrapper $gap="10px">
							<Button text="확인" theme="primary" type="submit" size="large" width="100%" handleClick={handleSingleModalClose} />
						</BtnWrapper>
					</Modal>

					{/* 비밀번호 초기화 모달 */}
					<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={initialModalClose}>
						<BtnWrapper $justify="flex-end">
							<ButtonClose onClick={handleInitialModalClose} />
						</BtnWrapper>
						<ModalText $align="center">비밀번호를 초기화하시겠습니까?</ModalText>
						<BtnWrapper $gap="10px">
							<Button text="취소" theme="line" size="large" width="100%" handleClick={handleInitialModalClose} />
							<Button text="확인" theme="primary" type="submit" size="large" width="100%" handleClick={handlePasswordInitialize} />
						</BtnWrapper>
					</Modal>
				</>
			)}
		</>
	);
}

export default AdminView;
