import CheckBox from '../../components/common/input/CheckBox';

import Modal from '../../components/common/modal/Modal';
import { Title, FormWrapper, SelectInput, TableInfo, ListCount, ListOption, TableStyle, BtnWrapper, ButtonClose, ModalText } from '../../styles/Components';
import Button from '../../components/common/button/Button';
import { useNavigate } from 'react-router-dom';
import { Fragment, useState, useEffect } from 'react';
import { GroupViewList, GroupDelete, GroupRegist } from '../../apis/Group';
import AuthRegistBar from '../../components/UserManage/AuthRegistBar';
import Pagination from '../../components/common/Pagination/Pagination';
import { authList } from '../../store/authList';
import { useRecoilValue } from 'recoil';
import AuthModal from '../../components/common/modal/AuthModal';
import { useTranslation } from 'react-i18next';
import { authType } from '../../assets/data';
import ViewTableInfo from '../../components/common/Table/ViewTableInfo';

const AuthSetting = () => {
	const token = sessionStorage.getItem('token');
	const userInfo = useRecoilValue(authList);
	const { t } = useTranslation();

	const navigate = useNavigate();

	const [doubleSubmitFlag, setDoubleSubmitFlag] = useState(false);

	const [dataList, setDataList] = useState([]);
	const [selectedRow, setSelectedRow] = useState([]);
	const [deleteModalClose, setDeleteModalClose] = useState('hidden');
	const [registModalClose, setRegistModalClose] = useState('hidden');
	const [confirmModalClose, setConfirmModalClose] = useState('hidden');
	const [isNullValue, setIsNullValue] = useState(false);

	const [confirmText, setConfirmText] = useState();

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

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

	const [registData, setRegistData] = useState({
		group_nm: '',
		description: '',
	});

	const fetchData = async (order, size) => {
		setDataList(await GroupViewList(token, order ? order : orderBy, currentPage, size ? size : pageSize, currentPage));
	};

	useEffect(() => {
		fetchData(orderBy, pageSize);
		setSelectedRow([]);
	}, [currentPage]);

	// 권한 등록 폼 제출
	const handleGroupSubmit = async () => {
		const message = await GroupRegist(token, registData);
		handleRegistModalClose();
		handleConfirmeModalClose();
		message.data.data.message !== '저장 하였습니다.' ? setConfirmText(message.data.data.message) : setConfirmText('등록이 완료되었습니다.');
	};

	const handleAllSelect = () => {
		let list = [];

		if (document.getElementById('check-all').checked === true) {
			dataList.group_list.map((data, index) => {
				document.getElementsByName('select')[index].checked = true;
				list.push(String(data.group_id));
			});
		} else if (document.getElementById('check-all').checked === false) {
			for (let i = 0; i < dataList.group_list.length; i++) {
				dataList.group_list.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 handleDeleteModalClose = () => {
		if (selectedRow.length !== 0 && deleteModalClose === 'hidden') {
			setDeleteModalClose('view');
			setConfirmText('삭제가 완료되었습니다.');
		} else {
			setDeleteModalClose('hidden');
		}
	};

	// 등록 확인 모달창
	const handleRegistModalClose = () => {
		if (registData.group_nm.length === 0) {
			// if(registData.group_nm.length === 0) {
			// 	setNullMessage("필수값을 입력해주세요.")
			// } else if(registData.group_nm.charAt(0) === " "){
			// 	setNullMessage("텍스트를 공백으로 시작할 수 없습니다.")
			// }

			setIsNullValue(true);
		} else if (registModalClose === 'hidden') {
			setRegistModalClose('view');
			setConfirmText('등록이 완료되었습니다.');
			setIsNullValue(false);
		} else {
			setRegistModalClose('hidden');
		}
	};

	//삭제, 등록 완료 모달창
	const handleConfirmeModalClose = () => {
		if (confirmModalClose === 'hidden') {
			setConfirmModalClose('view');
		} else {
			setConfirmModalClose('hidden');
			window.location.reload();
		}
	};

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

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

		GroupDelete(token, list);
		handleDeleteModalClose();
		handleConfirmeModalClose();
	};

	// 배열 정렬
	const handleOrderBy = e => {
		const order = e.target.value;

		setOrderBy(order);
		fetchData(order, pageSize);
	};

	const handlePageSize = e => {
		const size = e.target.value;
		setPageSize(size);
		setCurrentPage(1);

		fetchData(orderBy, size, 1);
	};

	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 === authType.authoritySettingRead) ? (
				<AuthModal />
			) : (
				<>
					<Title>권한 설정</Title>
					{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === authType.authoritySettingUpdate) && (
						<FormWrapper action="" $flow="row">
							<AuthRegistBar handleRegistModalClose={handleRegistModalClose} registData={registData} setRegistData={setRegistData} $isNullValue={isNullValue} nullMessage={t('NULL_MSG')} />
						</FormWrapper>
					)}
					<ViewTableInfo total={dataList.total} total_all={dataList.total_all} handleOrderBy={handleOrderBy} handlePageSize={handlePageSize}>
						{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === authType.authoritySettingDelete) && (
							<Button theme={selectedRow.length === 0 ? 'disable' : 'line'} text="선택 삭제" handleClick={handleDeleteModalClose} />
						)}
					</ViewTableInfo>
					<TableStyle>
						<caption></caption>
						<thead>
							<tr>
								<th width="40">
									<CheckBox id="check-all" handleCheck={handleAllSelect} checked={handleCountSelectedRow()} />
								</th>
								<th width="80">번호</th>
								<th width="20%">관리자 그룹명</th>
								<th width="150">그룹 인원</th>
								<th>설명</th>
								{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === authType.authoritySettingUpdate) ? <th width="120">권한 설정</th> : ''}
							</tr>
						</thead>
						<tbody>
							{dataList.group_list &&
								dataList.group_list.map(data => (
									<Fragment key={data.row_num}>
										<tr>
											<td>
												<CheckBox name={'select'} id={data.group_id} setData={e => handleSelectCheckBox(e)} />
											</td>
											<td>{data.row_num}</td>
											<td>{data.group_nm}</td>
											<td>{data.member_cnt}</td>
											<td>{data.description}</td>
											{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === authType.authoritySettingUpdate) && (
												<td>
													<Button
														theme="line"
														handleClick={e => {
															e.preventDefault();
															navigate(`/usermanage/authsetting/${data.group_id}`);
														}}
														text="수정"
													/>
												</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={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>
					{/* 등록 확인 모달 */}
					<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={registModalClose}>
						<BtnWrapper $justify="flex-end">
							<ButtonClose onClick={e => handleRegistModalClose(e)} />
						</BtnWrapper>
						<ModalText $align="center">신규 그룹을 등록하시겠습니까?</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 || handleGroupSubmit();
									setDoubleSubmitFlag(true);
								}}
							/>
						</BtnWrapper>
					</Modal>
				</>
			)}
		</>
	);
};

export default AuthSetting;
