import React, { Fragment, useState } from 'react';
import { Link } from 'react-router-dom';
import { useEffect } from 'react';

import Button from '../../components/common/button/Button';
import CheckBox from '../../components/common/input/CheckBox';
import Modal from '../../components/common/modal/Modal';

import styled from 'styled-components';
import {
	Title,
	TableWrapper,
	BtnWrapper,
	TableInfo,
	ListOption,
	TableStyle,
	ButtonClose,
	ModalText,
	DetailMessage,
} from '../../styles/Components';

import { NoticeDelete, NoticeDetailView, NoticeListView } from '../../apis/Notice';
import { BoardInfoModal, BoardRegistModal } from '../../components/ServiceManage';
import { authList } from '../../store/authList';
import { useRecoilValue } from 'recoil';
import { useNavigate } from 'react-router-dom';
import { convertKTC, timeDiffMinute } from '../../utils';
import AuthModal from '../../components/common/modal/AuthModal';
import { authType, landAuctionStatusType } from '../../assets/data';
import { useAlert } from '../../context/AlertProvider';
import { message_type, sendStatus } from '../../assets/data/options';
import { BattleEventDelete, BattleEventDetailView, BattleEventStop } from '../../apis/Battle';
import { alertTypes, battleEventStatusType } from '../../assets/data/types';
import { useModal, useTable, withAuth } from '../../hooks/hook';
import { useLoading } from '../../context/LoadingProvider';
import LogDetailModal from '../../components/common/modal/LogDetailModal';
import { historyTables } from '../../assets/data/data';
import { LogHistory } from '../../apis';
import { AnimatedPageWrapper } from '../../components/common/Layout';

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

	const [isCopyData, setIsCopyData] = useState(false);

	const [dataList, setDataList] = useState([]);
	const [detailView, setDetailView] = useState('hidden');
	const [registView, setRegistView] = useState('hidden');
	const [detailData, setDetailData] = useState('');
	const [detailId, setDetailId] = useState('');
	const [historyData, setHistoryData] = useState({});

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

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

	const fetchData = async () => {
		setDataList(await NoticeListView(token));
	};

	useEffect(() => {
		fetchData();
	}, []);

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

				await LogHistory(token, params).then(data => {
					setHistoryData(data);
					console.log(data);
					handleModalView('history');
				});
				break;
			case "detail":
				await NoticeDetailView(token, param.id).then(data => {
					setDetailData(data);
					setDetailId(param.id);
					setDetailView('view');
				});
				break;
			case "delete":
				if(selectedRows.length === 0) return;
				showModal('BOARD_DELETE_CONFIRM', {
					type: alertTypes.confirm,
					onConfirm: () => handleModalSubmit('deleteConfirm')
				});
				break;

			case "deleteConfirm":
				let list = [];

				selectedRows.map(data =>
					list.push({
						message_id: data.id,
					}),
				);

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

				break;
		}
	}

	return (
		<AnimatedPageWrapper>
			<Title>인게임 메시지</Title>
			<TableInfo>
				<ListOption>
					{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === authType.inGameDelete) && (
						<Button theme={selectedRows.length === 0 ? 'disable' : 'line'} text="선택 삭제" handleClick={() => handleModalSubmit('delete')} />
					)}
					{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === authType.inGameUpdate) && (
						<Button
							theme="primary"
							text="메시지 등록"
							value="2"
							handleClick={e => {
								e.preventDefault();
								setRegistView('view');
							}}
						/>
					)}
				</ListOption>
			</TableInfo>
			<TableWrapper>
				<TableStyle>
					<caption></caption>
					<thead>
						<tr>
							<th width="40">
							</th>
							<th width="80">번호</th>
							<th width="100">채팅 타입</th>
							<th width="200">송출 일자</th>
							<th>메시지</th>
							<th width="80">송출 횟수</th>
							<th width="100">송출 상태</th>
							<th width="120">히스토리</th>
						</tr>
					</thead>
					<tbody>
						{dataList &&
							dataList.map(notice => (
								<Fragment key={notice.id}>
									<tr>
										<td>
											<CheckBox name={'select'} id={notice.id}
													  setData={(e) => handleSelectRow(e, notice)}
													  checked={isRowSelected(notice.id)} />
										</td>
										<td>{notice.row_num}</td>
										<td>{message_type.find(item => item.value === notice.message_type)?.name}</td>
										<td>{convertKTC(notice.send_dt)}</td>
										<td>
											<DetailMessage
												onClick={() => handleModalSubmit('detail', { id: notice.id })}>
												{notice.content.length > 20 ? notice.content.slice(0, 20) + '...' : notice.content || ''}
											</DetailMessage>
										</td>
										<td>
											{/*{notice.send_cnt} / {notice.repeat_cnt}*/}
											{notice.send_cnt}
										</td>
										<td>
											{sendStatus.find(data => data.value === notice.send_status)?.name}
										</td>
										<td><Button theme="line" text="히스토리"
													handleClick={e => handleModalSubmit('history', notice)} />
										</td>
									</tr>
								</Fragment>
							))}
					</tbody>
				</TableStyle>
				{/* 인게임 메세지 정보 */}
				<BoardInfoModal
					detailView={detailView}
					setDetailView={setDetailView}
					content={detailData}
					id={detailId}
					setIsCopyData={setIsCopyData}
					openRegistModal={setRegistView}
					userInfo={userInfo}
				/>
				{/* 인게임 메세지 등록 */}
				<BoardRegistModal registView={registView} setRegistView={setRegistView} copyData={isCopyData ? detailData : ''} setIsCopyData={setIsCopyData} userInfo={userInfo} />
				<LogDetailModal
					viewMode="changed"
					detailView={modalState.historyModal}
					handleDetailView={() => handleModalClose('history')}
					changedData={historyData}
					title="히스토리"
				/>
			</TableWrapper>
		</AnimatedPageWrapper>
	);
};

export default withAuth(authType.inGameRead)(Board);


