import { useState, Fragment, useEffect } from 'react';
import Modal from '../../components/common/modal/Modal';
import Button from '../../components/common/button/Button';
import styled from 'styled-components';
import { Title, FormWrapper, TableStyle, TableWrapper, BtnWrapper, ButtonClose, ModalText } from '../../styles/Components';
import { useNavigate } from 'react-router-dom';
import { ItemsSearchBar } from '../../components/ServiceManage';
import { ItemListView } from '../../apis';

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

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

	const navigate = useNavigate();

	// 데이터 조회 관련
	const [dataList, setDataList] = useState([]);
	const [selectedData, setSelectedData] = useState([]);
	const [requestValue, setRequestValue] = useState([]);

	// 모달 관련 변수
	const [confirmDelModal, setConfirmDelModal] = useState('hidden');
	const [completeDelModal, setCompleteDelModal] = useState('hidden');
	const [confirmRestoreModal, setConfirmRestoreModal] = useState('hidden');
	const [completeRestoreModal, setCompleteRestoreModal] = useState('hidden');

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

	const status = [
		{ value: 'ALL', name: '상태' },
		{ value: 'ACTIVE', name: '활성' },
		{ value: 'DEACTIVE', name: '비활성' },
	];

	const restore = [
		{ value: 'ALL', name: '복구' },
		{ value: 'POSSIBLE', name: '가능' },
		{ value: 'IMPOSSIBLE', name: '불가능' },
	];

	const fetchData = async (searchType, data, status, restore) => {
		setDataList(await ItemListView(token, searchType, data, status, restore));
	};

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

	// 삭제 여부 모달
	const handleConfirmeDelModalClose = () => {
		if (confirmDelModal === 'hidden') {
			setConfirmDelModal('view');
		} else {
			setConfirmDelModal('hidden');
			setRequestValue([]);
		}
	};

	// 복구 여부 모달
	const handleConfirmeRestoreModalClose = () => {
		if (confirmRestoreModal === 'hidden') {
			setConfirmRestoreModal('view');
		} else {
			setConfirmRestoreModal('hidden');
			setRequestValue([]);
		}
	};

	// 삭제 모달창
	const handleConfirmDeleteModal = data => {
		handleConfirmeDelModalClose();
	};
	
	// 복구 모달창
	const handleConfirmRestoreModal = data => {
		handleConfirmeRestoreModalClose();
	};

	// 삭제 완료 확인 모달
	const handleCompleteDelModal = () => {
		if (completeDelModal === 'hidden') {
			setCompleteDelModal('view');
		} else {
			setCompleteDelModal('hidden');
			setRequestValue([]);
			handleConfirmeDelModalClose();
			window.location.reload();
		}
	};

	// 복구 완료 확인 모달
	const handleCompleteRestoreModal = () => {
		if (completeRestoreModal === 'hidden') {
			setCompleteRestoreModal('view');
		} else {
			setCompleteRestoreModal('hidden');
			setRequestValue([]);
			handleConfirmeRestoreModalClose();
			window.location.reload();
		}
	};

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

		list.push({ id: selectedData });
		
		// BlackListDelete(token, list);
		handleCompleteDelModal();
	};

	// 복구 기능
	const handleRestore = () => {
		let list = [];

		list.push({ id: selectedData});
		//api 호출

		handleCompleteRestoreModal();
	}

	return (
		<>
			{userInfo.auth_list && !userInfo.auth_list.some(auth => auth.id === authType.itemRead) ? (
				<AuthModal/>
			) : (
				<>
					<Title>아이템 복구 및 삭제</Title>
					<FormWrapper>
						<ItemsSearchBar handleSearch={handleSearch} setResultData={setSearchData} />
					</FormWrapper>
					<TableWrapper>
						<TableStyle>
							<caption></caption>
							<thead>
								<tr>
									<th width="80">번호</th>
									<th width="20%">아이템명</th>
									<th width="20%">아이템 ID</th>
									<th width="80">상태</th>
									<th width="100">생성 날짜</th>
									<th width="80">복구 가능 여부</th>
									{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === 30) && <th width="100">액션</th>}
								</tr>
							</thead>
							<tbody>
								{dataList.list &&
									dataList.list.map(data => (
										<Fragment key={data.id}>
											<tr>
												<td>{data.row_num}</td>
												<td>{data.item_nm}</td>
												<td>{data.item_id}</td>
												<td>{status.map(item => item.value === data.status && item.name)}</td>
												<td>{new Date(data.create_by).toLocaleString()}</td>
												<td>{restore.map(item => item.value === data.restore && item.name)}</td>
												{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === 30) && (
													<td>
														<ButtonGroup>
															<Button theme="line" id={data.id+"restore"} name="single" text="복구" handleClick={() => handleConfirmRestoreModal(data)} />
															<Divider>/</Divider>
															<Button theme="line" id={data.id+"delete"} name="single" text="삭제" handleClick={() => handleConfirmDeleteModal(data)} />
														</ButtonGroup>
													</td>
												)}
											</tr>
										</Fragment>
									))}
							</tbody>
						</TableStyle>
					</TableWrapper>

					{/* 삭제 확인 모달 */}
					<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={confirmDelModal}>
						<BtnWrapper $justify="flex-end">
							<ButtonClose onClick={handleConfirmeDelModalClose} />
						</BtnWrapper>
						<ModalText $align="center">
							아이템을 삭제하시겠습니까?<br />* 한번 삭제한 아이템은 다시 복구할 수 없습니다.
						</ModalText>
						<BtnWrapper $gap="10px">
							<Button text="취소" theme="line" size="large" width="100%" handleClick={handleConfirmeDelModalClose} />
							<Button text="확인" theme="primary" type="submit" size="large" width="100%" handleClick={handleDelete} />
						</BtnWrapper>
					</Modal>

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

					{/* 복구 확인 모달 */}
					<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={confirmRestoreModal}>
						<BtnWrapper $justify="flex-end">
							<ButtonClose onClick={handleConfirmeRestoreModalClose} />
						</BtnWrapper>
						<ModalText $align="center">
							아이템을 복구하시겠습니까?
						</ModalText>
						<BtnWrapper $gap="10px">
							<Button text="취소" theme="line" size="large" width="100%" handleClick={handleConfirmeRestoreModalClose} />
							<Button text="확인" theme="primary" type="submit" size="large" width="100%" handleClick={handleDelete} />
						</BtnWrapper>
					</Modal>

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

export default Items;

const ButtonGroup = styled.div`
	display: 'flex',
	alignItems: 'center'
`
const Divider = styled.span`
  margin: 0 8px;
  color: RGB(200,200,200);
  padding: 4px 0;
`; 