import { useState, useEffect, Fragment, memo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useRecoilValue } from 'recoil';
import { useTranslation } from 'react-i18next';

import {
	EventDelete,
	EventDetailView,
	EventView,
} from '../../apis';

import { authList } from '../../store/authList';
import { authType, commonStatus, modalTypes, eventStatus } from '../../assets/data';
import { Title, FormWrapper, TableStyle, MailTitle, TableWrapper, TextInput, InputItem } from '../../styles/Components';
import CheckBox from '../../components/common/input/CheckBox';
import Button from '../../components/common/button/Button';
import EventDetailModal from '../../components/ServiceManage/modal/EventDetailModal';
import Pagination from '../../components/common/Pagination/Pagination';
import 'react-datepicker/dist/react-datepicker.css';
import DynamicModal from '../../components/common/modal/DynamicModal';
import AuthModal from '../../components/common/modal/AuthModal';
import ViewTableInfo from '../../components/common/Table/ViewTableInfo';
import { convertKTC, timeDiffMinute } from '../../utils';
import EventListSearchBar from '../../components/ServiceManage/searchBar/EventListSearchBar';
import CustomConfirmModal from '../../components/common/modal/CustomConfirmModal';
import { ModalInputItem, ModalSubText, RegistInputItem, RegistNotice, SubText } from '../../styles/ModuleComponents';

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

	const navigate = useNavigate();

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

	const [dataList, setDataList] = useState([]);
	const [detailData, setDetailData] = useState('');

	const [selectedRow, setSelectedRow] = useState([]);
	const [searchData, setSearchData] = useState({
		title: '',
		content: '',
		status: 'ALL',
		startDate: '',
		endDate: '',
	});
	const [orderBy, setOrderBy] = useState('DESC');
	const [modalState, setModalState] = useState({
		detailModal: 'hidden',
		deleteConfirmModal: 'hidden',
		deleteCompleteModal: 'hidden',
	});
	const [alertMsg, setAlertMsg] = useState('');
	const [deleteDesc, setDeleteDesc] = useState('');

	useEffect(() => {
		fetchData('', '', 'ALL', '', '');
		setSelectedRow([]);
	}, [currentPage]);

	// 리스트 조회
	const fetchData = async (title, content, status, startDate, endDate, order, size) => {
		setDataList(
			await EventView(
				token,
				title,
				content,
				status,
				startDate && new Date(startDate).toISOString(),
				endDate && new Date(endDate).toISOString(),
				order ? order : orderBy,
				size ? size : pageSize,
				currentPage,
			),
		);
	};

	// 검색 함수
	const handleSearch = (title, content, status, startDate, endDate) => {
		fetchData(title, content, status, startDate && new Date(startDate).toISOString(), endDate && new Date(endDate).toISOString());
	};

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

		setOrderBy(order);
		fetchData(
			searchData.title,
			searchData.content,
			searchData.status,
			searchData.startDate && new Date(searchData.startDate).toISOString(),
			searchData.endDate && new Date(searchData.endDate).toISOString(),
			order,
			pageSize,
		);
	};

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

		fetchData(
			searchData.title,
			searchData.content,
			searchData.status,
			searchData.startDate && new Date(searchData.startDate).toISOString(),
			searchData.endDate && new Date(searchData.endDate).toISOString(),
			orderBy,
			size,
			1,
		);
	};

	// 상세보기 호출
	const handleDetailModal = async (e, id) => {
		await EventDetailView(token, id).then(data => {
			setDetailData(data);
		});

		e.preventDefault();
		handleModalView('detail');
	};

	// 체크박스 선택 리스트
	const handleSelectCheckBox = (e, event) => {
		let list = [...selectedRow];
		if (e.target.checked) {
			list.push(event);
			setSelectedRow(list);
		} else {
			const filterList = list.filter(data => e.target.id !== data);
			setSelectedRow(filterList);
		}
	};

	// 전체 선택 구현
	const handleAllSelect = () => {
		let list = [];
		if (document.getElementById('check-all').checked === true) {
			dataList.list.map((data, index) => {
				document.getElementsByName('select')[index].checked = true;
				list.push(String(data.id));
			});
		} 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 handleModalView = (type) => {
		setModalState((prevState) => ({
			...prevState,
			[`${type}Modal`]: 'view',
		}));
	}

	const handleModalClose = (type) => {
		setModalState((prevState) => ({
			...prevState,
			[`${type}Modal`]: 'hidden',
		}));
	}

	const handleModalSubmit = async (type, param = null) => {
		switch (type) {
			case "delete":
				const delete_check = selectedRow.every(row => {
					const timeDiff = timeDiffMinute(convertKTC(row.start_dt), (new Date));
					return row.add_flag || (timeDiff < 30);
				});
				if(delete_check){
					setAlertMsg(t('EVENT_TIME_LIMIT_UPDATE'));
					return;
				}
				handleModalView('deleteConfirm');
				break;
			case "deleteConfirm":
				let list = [];

				let isChecked = false;

				selectedRow.map(data => {
					const row = dataList.list.find(row => row.id === Number(data.id));
					if(row.status !== commonStatus.wait) isChecked = true;
					list.push({
						id: data.id,
						delete_desc: deleteDesc
					});
				});

				if(isChecked) {
					setAlertMsg(t('EVENT_WARNING_DELETE'))
					handleModalClose('deleteConfirm');
					return;
				}

				EventDelete(token, list);

				handleModalClose('deleteConfirm');
				handleModalView('deleteComplete');
				break;
			case "deleteComplete":
				handleModalClose('deleteComplete');
				// fetchData(option);
				window.location.reload();
				break;
			case "warning":
				setAlertMsg('')
				break;
		}
	}

	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.eventRead) ? (
				<AuthModal />
			) : (
				<>
					<Title>출석 보상 이벤트 관리</Title>
					<FormWrapper>
						<EventListSearchBar handleSearch={handleSearch} setResultData={setSearchData} />
					</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.eventDelete) && (
							<Button theme={selectedRow.length === 0 ? 'disable' : 'line'} text="선택 삭제" handleClick={() => handleModalSubmit('delete')} />
						)}
						{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === authType.eventUpdate) && (
							<Button
								theme="primary"
								text="이벤트 등록"
								type="button"
								handleClick={e => {
									e.preventDefault();
									navigate('/servicemanage/event/eventregist');
								}}
							/>
						)}
					</ViewTableInfo>
					<TableWrapper>
						<TableStyle>
							<caption></caption>
							<thead>
								<tr>
									<th width="40">
										<CheckBox id="check-all" handleCheck={handleAllSelect} checked={handleCountSelectedRow()} />
									</th>
									<th width="80">번호</th>
									<th width="100">이벤트 상태</th>
									<th width="210">시작 일시</th>
									<th width="210">종료 일시</th>
									<th>우편 제목</th>
									<th width="110">확인 / 수정</th>
									<th width="200">등록자(처리자)</th>
								</tr>
							</thead>
							<tbody>
								{dataList.list &&
									dataList.list.map(event => (
										<Fragment key={event.row_num}>
											<tr>
												<td>
													<CheckBox name={'select'} id={event.id} setData={e => handleSelectCheckBox(e, event)} />
												</td>
												<td>{event.row_num}</td>
												<td>{eventStatus.map(data => data.value === event.status && data.name)}</td>
												<td>{convertKTC(event.start_dt)}</td>
												<td>{convertKTC(event.end_dt)}</td>
												<MailTitle>{event.title}</MailTitle>
												<td>
													<Button theme="line" text="상세보기" handleClick={e => handleDetailModal(e, event.id)} />
												</td>
												<td>{event.create_by}</td>
											</tr>
										</Fragment>
									))}
							</tbody>
						</TableStyle>
					</TableWrapper>

					<Pagination postsPerPage={pageSize} totalPosts={dataList && dataList.total_all} setCurrentPage={setCurrentPage} currentPage={currentPage} pageLimit={10} />

					{/*상세*/}
					<EventDetailModal detailView={modalState.detailModal} handleDetailView={() => handleModalClose('detail')} content={detailData} setDetailData={setDetailData}/>

					{/*삭제 확인*/}
					<DynamicModal
						modalType={modalTypes.childOkCancel}
						view={modalState.deleteConfirmModal}
						handleCancel={() => handleModalClose('deleteConfirm')}
						handleSubmit={() => handleModalSubmit('deleteConfirm')}
					>
						<ModalInputItem>
							{t('EVENT_SELECT_DELETE')}
							<RegistInputItem>
								<TextInput
									placeholder="사유 입력"
									maxLength="30"
									value={deleteDesc}
									onChange={e => {
										if (e.target.value.length > 30) return;
										setDeleteDesc(e.target.value.trimStart())
									}}
								/>
							</RegistInputItem>
							<ModalSubText $color={deleteDesc.length > 29 ? 'red' : '#666'}>* 최대 등록 가능 글자수 ({deleteDesc.length}/30자)</ModalSubText>
						</ModalInputItem>
					</DynamicModal>
					{/*삭제 완료*/}
					<DynamicModal
						modalType={modalTypes.completed}
						view={modalState.deleteCompleteModal}
						handleSubmit={() => handleModalSubmit('deleteComplete')}
						modalText={t('DEL_COMPLETE')}
					/>
					{/* 경고 모달 */}
					<DynamicModal
						modalType={modalTypes.completed}
						view={alertMsg ? 'view' : 'hidden'}
						modalText={alertMsg}
						handleSubmit={() => handleModalSubmit('warning')}
					/>
				</>
			)}
		</>
	);
};

export default Event;
