import { 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 } from '../../utils';
import AuthModal from '../../components/common/modal/AuthModal';
import { authType } from '../../assets/data';

const Board = () => {
	const navigate = useNavigate();

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

	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 [selectedRow, setSelectedRow] = useState([]);
	const [deleteModalClose, setDeleteModalClose] = useState('hidden');
	const [confirmModalClose, setConfirmModalClose] = useState('hidden');

	const message_type = [
		{ value: 'CHATTING', name: '채팅 타입' },
		{ value: 'CHATTING_TOAST', name: '채팅 + 토스트' },
	];

	const sendStatus = [
		{ value: 'WAIT', name: '대기' },
		{ value: 'RUNNING', name: '송출중' },
		{ value: 'FINISH', name: '완료' },
		{ value: 'FAIL', name: '실패' },
	];

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

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

	// 체크박스 선택 리스트
	const handleSelectCheckBox = e => {
		let list = [...selectedRow];
		if (e.target.checked) {
			list.push(e.target.id);
			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.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.length; i++) {
				dataList.map((data, index) => (document.getElementsByName('select')[index].checked = false));
				list = [];
			}
		}
		setSelectedRow(list);
	};

	// 선택 삭제 함수
	const handleSelectedDelete = () => {
		let list = [];

		selectedRow.map(data =>
			list.push({
				message_id: data,
			}),
		);
		NoticeDelete(token, list);

		handleDeleteModalClose();
		handleConfirmeModalClose();
	};

	// 선택 삭제 모달
	const handleDeleteModalClose = () => {
		if (selectedRow.length !== 0 && deleteModalClose === 'hidden') {
			setDeleteModalClose('view');
		} else {
			setDeleteModalClose('hidden');
		}
	};

	// 삭제, 승인, 저장 확인 모달창
	const handleConfirmeModalClose = () => {
		if (confirmModalClose === 'hidden') {
			setConfirmModalClose('view');
		} else {
			setConfirmModalClose('hidden');
			window.location.reload();
		}
	};

	const handleDetailModal = async (e, id) => {
		setDetailData(await NoticeDetailView(token, id));
		setDetailId(id);

		e.preventDefault();
		setDetailView('view');
	};

	const handleCountSelectedRow = () => {
		return dataList && document.querySelectorAll('input[name="select"]:checked').length === dataList.length;
	};

	return (
		<>
			{userInfo.auth_list && !userInfo.auth_list.some(auth => auth.id === authType.inGameRead) ? (
				<AuthModal/>
			) : (
				<>
					<Title>인게임 메시지</Title>
					<TableInfo>
						<ListOption>
							{userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === authType.inGameDelete) && (
								<Button theme={selectedRow.length === 0 ? 'disable' : 'line'} text="선택 삭제" handleClick={handleDeleteModalClose} />
							)}
							{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">
										<CheckBox id="check-all" handleCheck={handleAllSelect} checked={handleCountSelectedRow()} />
									</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>
									<th width="200">등록자(이메일주소)</th>
									<th width="200">등록일자</th>
								</tr>
							</thead>
							<tbody>
								{dataList &&
									dataList.map(notice => (
										<Fragment key={notice.id}>
											<tr>
												<td>
													<CheckBox name={'select'} id={notice.id} setData={e => handleSelectCheckBox(e)} />
												</td>
												<td>{notice.row_num}</td>
												<td>{message_type.map(item => item.value === notice.message_type && item.name)}</td>
												<td>{convertKTC(notice.send_dt)}</td>
												<td>
													<DetailMessage onClick={e => handleDetailModal(e, 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.map(data => data.value === notice.send_status && data.name)}
												</td>
												<td>{notice.create_name}</td>
												<td>{notice.create_by}</td>
												<td>{convertKTC(notice.create_dt)}</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} />
					</TableWrapper>

					{/* 선택 삭제 모달 */}
					<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={deleteModalClose}>
						<BtnWrapper $justify="flex-end">
							<ButtonClose onClick={handleDeleteModalClose} />
						</BtnWrapper>
						<ModalText $align="center">
							선택된 인게임 메세지를 삭제하시겠습니까?
							<br />
							삭제 시 설정 정보가 제거됩니다.
						</ModalText>
						<BtnWrapper $gap="10px">
							<Button text="취소" theme="line" size="large" width="100%" handleClick={handleDeleteModalClose} />
							<Button text="확인" theme="primary" type="submit" size="large" width="100%" handleClick={handleSelectedDelete} />
						</BtnWrapper>
					</Modal>
					{/* 확인 모달 */}
					<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={confirmModalClose}>
						<BtnWrapper $justify="flex-end">
							<ButtonClose onClick={handleConfirmeModalClose} />
						</BtnWrapper>
						<ModalText $align="center">삭제가 완료되었습니다.</ModalText>
						<BtnWrapper $gap="10px">
							<Button text="확인" theme="primary" type="submit" size="large" width="100%" handleClick={handleConfirmeModalClose} />
						</BtnWrapper>
					</Modal>
				</>
			)}
		</>
	);
};

export default Board;


