import styled from 'styled-components';
import React, { useState, Fragment } from 'react';

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

import { LogHistory, MailDelete, MailDetailView } from '../../apis';

import { Title, FormWrapper, TableStyle, MailTitle, TableWrapper } from '../../styles/Components';
import Button from '../../components/common/button/Button';

import 'react-datepicker/dist/react-datepicker.css';
import { useNavigate } from 'react-router-dom';
import MailDetailModal from '../../components/modal/MailDetailModal';
import Pagination from '../../components/common/Pagination/Pagination';

import { authList } from '../../store/authList';
import { useRecoilValue } from 'recoil';
import {
	authType,
	mailReceiveType,
	mailSendStatus,
	mailSendType,
	mailType,
} from '../../assets/data';
import ViewTableInfo from '../../components/common/Table/ViewTableInfo';
import { convertKTC } from '../../utils';
import { StatusLabel, StatusWapper } from '../../styles/ModuleComponents';
import { CommonSearchBar, useCommonSearch } from '../../components/ServiceManage';
import { INITIAL_PAGE_LIMIT } from '../../assets/data/adminConstants';
import { alertTypes } from '../../assets/data/types';
import { useModal, useTable, withAuth } from '../../hooks/hook';
import { useAlert } from '../../context/AlertProvider';
import { useLoading } from '../../context/LoadingProvider';
import useCommonSearchOld from '../../hooks/useCommonSearchOld';
import LogDetailModal from '../../components/common/modal/LogDetailModal';
import { historyTables } from '../../assets/data/data';

const Mail = () => {
	const token = sessionStorage.getItem('token');
	const userInfo = useRecoilValue(authList);
	const {showModal, showToast} = useAlert();
	const {withLoading} = useLoading();
	const navigate = useNavigate();

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

	const {
		modalState,
		handleModalView,
		handleModalClose
	} = useModal({
		detail: 'hidden',
		history: 'hidden'
	});

	const {
		config,
		searchParams,
		data: dataList,
		handleSearch,
		handleReset,
		handlePageChange,
		handlePageSizeChange,
		handleOrderByChange,
		updateSearchParams,
		configLoaded
	} = useCommonSearchOld("mailSearch");

	const {
		selectedRows,
		handleSelectRow,
		isRowSelected
	} = useTable(dataList?.list || [], {mode: 'single'});

	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.mail

				await LogHistory(token, params).then(data => {
					setHistoryData(data);
					handleModalView('history');
				});
				break;
			case "detail":
				await MailDetailView(token, param).then(data => {
					setDetailData(data);
					handleModalView('detail');
				});
				break;
			case "delete":
				if(selectedRows.length === 0) return;

				showModal('MAIL_SELECT_DELETE', {
					type: alertTypes.confirm,
					onConfirm: () => handleModalSubmit('deleteConfirm')
				});
				break;

			case "deleteConfirm":
				let list = [];

				let isChecked = false;

				selectedRows.map(data => {
					const row = dataList.list.find(row => row.id === Number(data.id));
					if(row.send_status === "FINISH" || row.send_status === "RUNNING" || row.send_status === "FAIL") isChecked = true;
					list.push({
						id: data.id,
					});
				});

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

				withLoading( async () => {
					return await MailDelete(token, list);
				}).then(data => {
					showToast('DEL_COMPLETE', {type: alertTypes.success});
				}).catch(reason => {
					showToast('API_FAIL', {type: alertTypes.error});
				}).finally(() => {
					handleSearch(updateSearchParams);
				});

				break;
		}
	}

	return (
		<>
			<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.mailDelete) && (
					<Button theme={selectedRows.length === 0 ? 'disable' : 'line'} text="선택 삭제" handleClick={() => handleModalSubmit('delete')} />
				)}
				{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === authType.mailUpdate) && (
					<Button
						theme="primary"
						text="우편 등록"
						type="button"
						handleClick={e => {
							e.preventDefault();
							navigate('/servicemanage/mail/mailregist');
						}}
					/>
				)}
			</ViewTableInfo>
			<TableWrapper>
				<TableStyle>
					<caption></caption>
					<thead>
						<tr>
							<th width="40">
							</th>
							<th width="80">번호</th>
							<th width="210">등록 일시</th>
							<th width="210">발송 일시</th>
							<th width="100">발송 방식</th>
							<th width="100">발송 상태</th>
							<th width="100">우편 타입</th>
							<th width="100">수신 대상</th>
							<th>우편 제목</th>
							<th width="110">확인 / 수정</th>
							<th width="200">히스토리</th>
						</tr>
					</thead>
					<tbody>
						{dataList?.list?.map(mail => (
								<Fragment key={mail.row_num}>
									<tr>
										<td>
											<CheckBox name={'select'} id={mail.id}
													  setData={(e) => handleSelectRow(e, mail)}
													  checked={isRowSelected(mail.id)} />
										</td>
										<td>{mail.row_num}</td>
										<td>{convertKTC(mail.create_dt)}</td>
										<td>{convertKTC(mail.send_dt)}</td>
										<td>{mailSendType.map(data => data.value === mail.send_type && data.name)}</td>
										<StatusWapper>
											<StatusLabel $status={mail.send_status}>
												{mailSendStatus.map(data => data.value === mail.send_status && data.name)}
											</StatusLabel>
										</StatusWapper>
										<td>{mailType.map(data => data.value === mail.mail_type && data.name)}</td>
										<td>{mailReceiveType.map(data => data.value === mail.receive_type && data.name)}</td>
										<MailTitle>{mail.title}</MailTitle>
										<td>
											<Button theme="line" text="상세보기"
													handleClick={e => handleModalSubmit('detail', mail.id)} />
										</td>
										<td><Button theme="line" text="히스토리"
													handleClick={e => handleModalSubmit('history', mail)} />
										</td>
									</tr>
								</Fragment>
						))}
					</tbody>
				</TableStyle>
			</TableWrapper>
			<Pagination postsPerPage={searchParams.pageSize} totalPosts={dataList?.total_all} setCurrentPage={handlePageChange} currentPage={searchParams.currentPage} pageLimit={INITIAL_PAGE_LIMIT} />

			<MailDetailModal
				detailView={modalState.detailModal}
				handleDetailView={() =>{
					handleModalClose('detail');
					handleSearch(updateSearchParams);
				}}
				content={detailData}
			/>

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

		</>
	);
};

export default withAuth(authType.mailRead)(Mail);

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