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

import {
	EventDelete,
	EventDetailView, LogHistory,
} 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 {
	ModalInputItem,
	ModalSubText,
	RegistInputItem,
	StatusLabel, StatusWapper,
} from '../../styles/ModuleComponents';
import { useLoading } from '../../context/LoadingProvider';
import { useAlert } from '../../context/AlertProvider';
import { CommonSearchBar, useCommonSearch } from '../../components/ServiceManage';
import { useModal, useTable } from '../../hooks/hook';
import { INITIAL_PAGE_LIMIT } from '../../assets/data/adminConstants';
import { alertTypes } from '../../assets/data/types';
import useCommonSearchOld from '../../hooks/useCommonSearchOld';
import { historyTables } from '../../assets/data/data';
import LogDetailModal from '../../components/common/modal/LogDetailModal';

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

	const navigate = useNavigate();
	const [detailData, setDetailData] = useState('');
	const [historyData, setHistoryData] = useState({});

	const {
		modalState,
		handleModalView,
		handleModalClose
	} = useModal({
		detail: 'hidden',
		delete: 'hidden',
		history: 'hidden'
	});
	const [deleteDesc, setDeleteDesc] = useState('');

	const {
		config,
		searchParams,
		data: dataList,
		handleSearch,
		handleReset,
		handlePageChange,
		handlePageSizeChange,
		handleOrderByChange,
		updateSearchParams,
		configLoaded
	} = useCommonSearchOld("eventSearch");
	const {
		selectedRows,
		handleSelectRow,
		isRowSelected
	} = useTable(dataList?.list || [], {mode: 'single'});

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

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


	const handleModalSubmit = async (type, param = null) => {
		switch (type) {
			case "history":
				const params = {};
				params.db_type = "MYSQL"
				params.sql_id = param.id;
				params.table_name = historyTables.event

				await LogHistory(token, params).then(data => {
					setHistoryData(data);
					handleModalView('history');
				});
				break;
			case "delete":
				const delete_check = selectedRows.every(row => {
					const timeDiff = timeDiffMinute(convertKTC(row.start_dt), (new Date));
					return row.add_flag || (timeDiff < 30);
				});
				if(delete_check){
					showToast('EVENT_TIME_LIMIT_UPDATE', {type: alertTypes.warning});
					return;
				}

				handleModalView('delete');
				break;
			case "deleteConfirm":
				let list = [];

				if(deleteDesc.length === 0){
					showToast('INPUT_REASON_EMPTY_WARNING', {type: alertTypes.warning});
					return;
				}

				let isChecked = false;

				selectedRows.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
					});
				});

				handleModalClose('delete');
				setDeleteDesc('');

				if(isChecked) {
					showToast('EVENT_WARNING_DELETE', {type: alertTypes.warning});
					return;
				}

				await withLoading(async () => {
					return await EventDelete(token, list);
				}).then(data => {
					showToast('DEL_COMPLETE', {type: alertTypes.success});
				}).catch(error => {

				}).finally(() => {
					handleSearch(updateSearchParams);
				})

				break;
		}
	}

	return (
		<>
			{userInfo.auth_list && !userInfo.auth_list.some(auth => auth.id === authType.eventRead) ? (
				<AuthModal />
			) : (
				<>
					<Title>출석 보상 이벤트 관리</Title>
					<FormWrapper>
						<CommonSearchBar
							config={config}
							searchParams={searchParams}
							onSearch={(newParams, executeSearch = true) => {
								if (executeSearch) {
									handleSearch(newParams);
								} else {
									updateSearchParams(newParams);
								}
							}}
							onReset={handleReset}
						/>
					</FormWrapper>
					<ViewTableInfo total={dataList?.total} total_all={dataList?.total_all} handleOrderBy={handleOrderByChange} handlePageSize={handlePageSizeChange}>
						{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === authType.eventDelete) && (
							<Button theme={selectedRows.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">
									</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?.map(event => (
										<Fragment key={event.row_num}>
											<tr>
												<td>
													<CheckBox name={'select'} id={event.id}
															  setData={(e) => handleSelectRow(e, event)}
															  checked={isRowSelected(event.id)} />
												</td>
												<td>{event.row_num}</td>
												<StatusWapper>
													<StatusLabel $status={event.status}>
														{eventStatus.map(data => data.value === event.status && data.name)}
													</StatusLabel>
												</StatusWapper>
												<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><Button theme="line" text="히스토리"
															handleClick={e => handleModalSubmit('history', event)} />
												</td>
											</tr>
										</Fragment>
								))}
							</tbody>
						</TableStyle>
					</TableWrapper>

					<Pagination postsPerPage={searchParams.pageSize} totalPosts={dataList?.total_all} setCurrentPage={handlePageChange} currentPage={searchParams.currentPage} pageLimit={INITIAL_PAGE_LIMIT} />

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

					<LogDetailModal
						viewMode="changed"
						detailView={modalState.historyModal}
						handleDetailView={() => handleModalClose('history')}
						changedData={historyData}
						title="히스토리"
					/>

					<DynamicModal
						modalType={modalTypes.childOkCancel}
						view={modalState.deleteModal}
						handleCancel={() => handleModalClose('delete')}
						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>
				</>
			)}
		</>
	);
};

export default Event;
