import { useState, Fragment, useEffect } from 'react';
import CheckBox from '../../components/common/input/CheckBox';
import Modal from '../../components/common/modal/Modal';
import Button from '../../components/common/button/Button';
import styled from 'styled-components';
import { Title, FormWrapper, TableInfo, ListCount, ListOption, TableStyle, SelectInput, TableWrapper, BtnWrapper, ButtonClose, ModalText } from '../../styles/Components';
import { useNavigate } from 'react-router-dom';
import { UserBlockDetailModal, UserBlockSearchBar } from '../../components/ServiceManage/';
import { BlackListView, BlackListDetail, BlackListDelete } from '../../apis';
import Pagination from '../../components/common/Pagination/Pagination';

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

const UserBlock = () => {
	const token = sessionStorage.getItem('token');
	const userInfo = useRecoilValue(authList);

	const navigate = useNavigate();

	// 페이지 네이션 관련
	const [currentPage, setCurrentPage] = useState(1);
	const [pageSize, setPageSize] = useState(50);

	// 데이터 조회 관련
	const [dataList, setDataList] = useState([]);
	const [detailView, setDetailView] = useState('hidden');
	const [selectedRow, setSelectedRow] = useState([]);
	const [selectedData, setSelectedData] = useState([]);
	const [detail, setDetail] = useState([]);
	const [requestValue, setRequestValue] = useState([]);

	// 모달 관련 변수
	const [confirmModal, setConfirmModal] = useState('hidden');
	const [completeModal, setCompleteModal] = useState('hidden');

	// 검색 관련 변수
	const [orderBy, setOrderBy] = useState('DESC');
	const [searchData, setSearchData] = useState({
		searchType: 'GUID',
		searchKey: '',
		status: 'ALL',
		sanctions: 'ALL',
		period: 'ALL',
	});

	// 등록하기 모달 연결
	const handleDetail = async dataValue => {
		if (detailView === 'hidden') {
			setDetailView('block');
		} else {
			setDetailView('hidden');
			setDetail([]);
		}

		setSelectedData(dataValue);

		const id = dataValue.id;

		if (id) {
			setDetail(await BlackListDetail(token, id));
		}
	};

	const fetchData = async (searchType, data, email, status, sanctions, period, order, size) => {
		setDataList(await BlackListView(token, searchType, data, email, status, sanctions, period, order ? order : orderBy, size ? size : pageSize, currentPage));
	};

	// 검색 기능
	const handleSearch = (searchType, data, email, status, sanctions, period) => {
		fetchData(searchType, data, email, status, sanctions, period);
	};

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

		setOrderBy(order);
		fetchData(searchData.searchType, searchData.searchKey, searchData.email, searchData.status, searchData.sanctions, searchData.period, order, pageSize);
	};

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

		fetchData(searchData.searchType, searchData.searchKey, searchData.email, searchData.status, searchData.sanctions, searchData.period, orderBy, size, 1);
	};

	useEffect(() => {
		fetchData(searchData.searchType, searchData.searchKey, searchData.email, searchData.status, searchData.sanctions, searchData.period, orderBy, pageSize);
		setSelectedRow([]);
	}, [currentPage]);

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

		if (checkAll.checked === true) {
			dataList.list.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.list.length; i++) {
				dataList.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 handleConfirmeModalClose = () => {
		if (confirmModal === 'hidden') {
			setConfirmModal('view');
		} else {
			setConfirmModal('hidden');
			setRequestValue([]);
		}
	};

	// 선택, 복수 삭제 모달창
	const handleConfirmModal = data => {
		if (data.id) {
			setSelectedData(data.id);
			if (selectedData) {
				setRequestValue(data.id);
			}
		} else if (selectedRow) {
			setRequestValue(selectedRow);
		}

		handleConfirmeModalClose();
	};

	// 완료 확인 모달
	const handleCompleteModal = () => {
		if (completeModal === 'hidden') {
			setCompleteModal('view');
		} else {
			setCompleteModal('hidden');
			setRequestValue([]);
			handleConfirmeModalClose();
			window.location.reload();
		}
	};

	// 삭제 기능 구현
	const handleDelete = () => {
		let list = [];

		if (requestValue === selectedRow) {
			selectedRow.map(data =>
				list.push({
					id: data,
				}),
			);
			BlackListDelete(token, list);
			// console.log(list);
			// console.log(selectedRow);
			handleCompleteModal();
		} else if (requestValue !== selectedRow) {
			list.push({ id: selectedData });
			// console.log(list);
			BlackListDelete(token, list);
			handleCompleteModal();
		}
	};

	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.blackListRead) ? (
				<AuthModal/>
			) : (
				<>
					<Title>이용자 제재 조회 및 등록</Title>
					<FormWrapper>
						<UserBlockSearchBar handleSearch={handleSearch} setResultData={setSearchData} />
					</FormWrapper>
					<TableInfo>
						<ListCount>
							총 : {dataList && dataList.total} 건 / {dataList && dataList.total_all} 건
						</ListCount>
						<ListOption>
							<SelectInput
								name=""
								id=""
								className="input-select"
								onChange={e => {
									handleOrderBy(e);
								}}>
								<option value="DESC">내림차순</option>
								<option value="ASC">오름차순</option>
							</SelectInput>
							<SelectInput
								name=""
								id=""
								onChange={e => {
									handlePageSize(e);
								}}
								className="input-select">
								<option value="50">50개</option>
								<option value="100">100개</option>
							</SelectInput>
							{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === 30) && (
								<Button theme={selectedRow.length === 0 ? 'disable' : 'line'} type="submit" text="선택 삭제" id={selectedRow} handleClick={() => handleConfirmModal(selectedRow)} />
							)}
							{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === 25) && (
								<Button
									theme="primary"
									type="submit"
									text="제재 등록"
									handleClick={e => {
										e.preventDefault();
										navigate('/servicemanage/userblock/userblockregist');
									}}
								/>
							)}
						</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="20%">GUID</th>
									<th width="20%">아바타명</th>
									<th width="100">상태</th>
									<th width="100">제재 기간</th>
									<th width="250">제재 사유</th>
									<th width="150">등록자</th>
									<th width="110">상세정보</th>
									{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === 30) && <th width="80">삭제</th>}
								</tr>
							</thead>
							<tbody>
								{dataList.list &&
									dataList.list.map(data => (
										<Fragment key={data.id}>
											<tr>
												<td>
													<CheckBox name={'select'} id={data.id} setData={e => handleSelectCheckBox(e)} />
												</td>
												<td>{data.row_num}</td>
												<td>{data.guid}</td>
												<td>{data.nickname}</td>
												{data.status === 'INPROGRESS' ? (
													<td>
														<ListState>{blockStatus.map(item => item.value === data.status && item.name)}</ListState>
													</td>
												) : (
													<td>{blockStatus.map(item => item.value === data.status && item.name)}</td>
												)}
												<td>{blockPeriod.map(item => item.value === data.period && item.name)}</td>
												<td>{blockSanctions.map(item => item.value === data.sanctions && item.name)}</td>
												<td>{data.create_by}</td>
												<td>
													<Button theme="line" text="상세보기" handleClick={() => handleDetail(data)} />
												</td>
												{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === 30) && (
													<td>
														<Button theme="line" id={data.id} name="single" text="삭제" handleClick={() => handleConfirmModal(data)} />
													</td>
												)}
											</tr>
										</Fragment>
									))}
							</tbody>
						</TableStyle>
					</TableWrapper>
					<Pagination postsPerPage={pageSize} totalPosts={dataList && dataList.total_all} setCurrentPage={setCurrentPage} currentPage={currentPage} pageLimit={10} />
					<UserBlockDetailModal stateModal={detailView} data={detail} handleModal={handleDetail} />

					{/* 선택 삭제 모달 */}
					<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={confirmModal}>
						<BtnWrapper $justify="flex-end">
							<ButtonClose onClick={handleConfirmeModalClose} />
						</BtnWrapper>
						<ModalText $align="center">
							제재 대상을 삭제하시겠습니까?
							<br />
							삭제 시 제재가 해제됩니다.
						</ModalText>
						<BtnWrapper $gap="10px">
							<Button text="취소" theme="line" size="large" width="100%" handleClick={handleConfirmeModalClose} />
							<Button text="확인" theme="primary" type="submit" size="large" width="100%" handleClick={handleDelete} />
						</BtnWrapper>
					</Modal>

					{/* 완료창 모달 */}

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

export default UserBlock;

const ListState = styled.span`
	color: #d60000;
`;
