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

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

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

import { Title, FormWrapper, TableInfo, ListCount, ListOption, TableStyle, SelectInput, MailTitle, TableWrapper, BtnWrapper, ButtonClose, ModalText } 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/ServiceManage/modal/MailDetailModal';
import MailListSearchBar from '../../components/ServiceManage/searchBar/MailListSearchBar';
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 AuthModal from '../../components/common/modal/AuthModal';
import ViewTableInfo from '../../components/common/Table/ViewTableInfo';
import { convertKTC} from '../../utils';

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

	const navigate = useNavigate();

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

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

	const [selectedRow, setSelectedRow] = useState([]);
	const [searchData, setSearchData] = useState({
		mailTitle: '',
		content: '',
		sendType: 'ALL',
		sendStatus: 'ALL',
		mailType: 'ALL',
		receiveType: 'ALL',
		sendDate: '',
		endDate: '',
	});
	const [orderBy, setOrderBy] = useState('DESC');

	const [deleteModalClose, setDeleteModalClose] = useState('hidden');
	const [confirmModalClose, setConfirmModalClose] = useState('hidden');

	// console.log(dataList);

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

	// 리스트 조회
	const fetchData = async (mailTitle, content, sendType, sendStatus, mailType, receiveType, sendDate, endDate, order, size) => {
		setDataList(
			await MailView(
				token,
				mailTitle,
				content,
				sendType,
				sendStatus,
				mailType,
				receiveType,
				sendDate && new Date(sendDate).toISOString(),
				endDate && new Date(endDate).toISOString(),
				order ? order : orderBy,
				size ? size : pageSize,
				currentPage,
			),
		);
	};

	// 검색 함수
	const handleSearch = (mailTitle, content, sendType, sendStatus, mailType, receiveType, sendDate, endDate) => {
		fetchData(mailTitle, content, sendType, sendStatus, mailType, receiveType, sendDate && new Date(sendDate).toISOString(), endDate && new Date(endDate).toISOString());
	};

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

		setOrderBy(order);
		fetchData(
			searchData.mailTitle,
			searchData.content,
			searchData.sendType,
			searchData.sendStatus,
			searchData.mailType,
			searchData.receiveType,
			searchData.sendDate && new Date(searchData.sendDate).toISOString(),
			searchData.endDate && new Date(searchData.endDate).toISOString(),
			order,
			pageSize,
		);
	};

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

		fetchData(
			searchData.mailTitle,
			searchData.content,
			searchData.sendType,
			searchData.sendStatus,
			searchData.mailType,
			searchData.receiveType,
			searchData.sendDate && new Date(searchData.sendDate).toISOString(),
			searchData.endDate && new Date(searchData.endDate).toISOString(),
			orderBy,
			size,
			1,
		);
	};

	const handleDetailView = () => {
		if (detailView === 'hidden') setDetailView('view');
		else setDetailView('hidden');
	};

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

		e.preventDefault();
		handleDetailView();
	};

	// 체크박스 선택 리스트
	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.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 handleSelectedDelete = () => {
		let list = [];

		let isChecked = false;

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

		if(isChecked) {
			alert("발송 완료한 우편은 삭제할 수 없습니다.")
			handleDeleteModalClose();
			return;
		}

		MailDelete(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 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.mailRead) ? (
				<AuthModal/>
			) : (
				<>
					<Title>우편 조회 및 발송 관리</Title>
					<FormWrapper>
						<MailListSearchBar 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.mailDelete) && (
							<Button theme={selectedRow.length === 0 ? 'disable' : 'line'} text="선택 삭제" handleClick={handleDeleteModalClose} />
						)}
						{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">
										<CheckBox id="check-all" handleCheck={handleAllSelect} checked={handleCountSelectedRow()} />
									</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 &&
									dataList.list.map(mail => (
										<Fragment key={mail.row_num}>
											<tr>
												<td>
													<CheckBox name={'select'} id={mail.id} setData={e => handleSelectCheckBox(e)} />
												</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>
												<td>
													{mail.send_status === 'FAIL' ? (
														<ListState>{mailSendStatus.map(data => data.value === mail.send_status && data.name)}</ListState>
													) : (
														mailSendStatus.map(data => data.value === mail.send_status && data.name)
													)}
												</td>
												<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 => handleDetailModal(e, mail.id)} />
												</td>
												<td>{mail.create_by}</td>
											</tr>
										</Fragment>
									))}
							</tbody>
						</TableStyle>
					</TableWrapper>
					<Pagination postsPerPage={pageSize} totalPosts={dataList && dataList.total_all} setCurrentPage={setCurrentPage} currentPage={currentPage} pageLimit={10} />

					<MailDetailModal detailView={detailView} handleDetailView={handleDetailView} content={detailData} />
					{/* 선택 삭제 모달 */}
					<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 Mail;

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