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

import styled from 'styled-components';

import CheckBox from '../../components/common/input/CheckBox';
import MailDetailModal from '../../components/DataManage/MailDetailModal';
import { SelectInput, TextInput } from '../../styles/Components';
import { UserMailDelete, UserMailItemDelete, UserMailView } from '../../apis';
import ConfirmModal from '../common/modal/ConfirmModal';
import CompletedModal from '../common/modal/CompletedModal';
import { useTranslation } from 'react-i18next';
import CustomConfirmModal from '../common/modal/CustomConfirmModal';
import DynamicModal from '../common/modal/DynamicModal';
import { authType, ivenTabType } from '../../assets/data';
import { useRecoilValue } from 'recoil';
import { authList } from '../../store/authList';
import { convertKTC } from '../../utils';
import { TableSkeleton } from '../Skeleton/TableSkeleton';

const UserMailInfo = ({ userInfo }) => {
	const token = sessionStorage.getItem('token');
	const { t } = useTranslation();
	const authInfo = useRecoilValue(authList);

	//데이터 리스트
	const [dataList, setDataList] = useState([]);
	// 받은 우편, 보낸 우편
	const [option, setOption] = useState('RECEIVE');
	// 상세 정보
	const [detail, setDetail] = useState({ title: '', content: '', item_list: [], mail_guid: '' });
	const [deleteSelected, setDeleteSelected] = useState({});
	const [itemUpdateCount, setItemUpdateCount] = useState('1');
	const [authDelete, setAuthDelete] = useState(false);
	const [loading, setLoading] = useState(true);

	const [modalState, setModalState] = useState({
		detailModal: 'hidden',
		deleteItemModal: 'hidden',
		deleteSubmitModal: 'hidden',
		deleteCompleteModal: 'hidden',
		deleteItemCompleteModal: 'hidden'
	});

	// 받은 우편, 보낸 우편 option 에 따른 data fetch
	useEffect(() => {
		fetchData(option);
	}, [option]);

	useEffect(() => {
		setAuthDelete(authInfo.auth_list.some(auth => auth.id === authType.userSearchDelete));
	}, [authInfo]);

	const fetchData = async option => {
		await UserMailView(token, userInfo.guid, option).then(data =>{
			setDataList(data);
			setLoading(false);
		});
	};

	// 상세 모달 value 세팅
	const handleDetail = (title, content, itmeList, mail_guid) => {
		setDetail({ title: title, content: content, item_list: itmeList, mail_guid: mail_guid });
	};

	// 우편 아이템 삭제 개수 처리
	const handleItemCount = e => {
		if (e.target.value === '0' || e.target.value === '-0') {
			setItemUpdateCount('1');
			e.target.value = '1';
		} else if (e.target.value < 0) {
			let plusNum = Math.abs(e.target.value);
			setItemUpdateCount(plusNum);
		} else if(e.target.value > deleteSelected.count){
			alert(t('DEL_COUNT_CHECK'));
			setItemUpdateCount(deleteSelected.count);
		} else {
			setItemUpdateCount(e.target.value);
		}
	};

	const handleModalView = (type) => {
		setModalState((prevState) => ({
			...prevState,
			[`${type}Modal`]: 'view',
		}));
	}

	const handleModalClose = (type) => {
		setModalState((prevState) => ({
			...prevState,
			[`${type}Modal`]: 'hidden',
		}));
	}

	const handleModalSubmit = async (type, param = null) => {
		let params;
		let result;
		switch (type) {
			case "detail":
				handleModalView('deleteSubmit');
				break;
			case "deleteItem":
				setDeleteSelected(param);
				handleModalView('deleteItem');
				break;
			case "deleteSubmit":
				params = {}
				params.type = option;
				params.guid = userInfo.guid;
				params.mail_guid = detail.mail_guid;

				result = await UserMailDelete(token, params);

				handleModalClose('deleteSubmit');
				handleModalView('deleteComplete');
				break;
			case "deleteItemSubmit":
				params = {}
				params.type = option;
				params.guid = userInfo.guid;
				params.mail_guid = detail.mail_guid;
				params.item_id = deleteSelected.item_id;
				params.parrent_count = deleteSelected.count;
				params.count = itemUpdateCount;

				result = await UserMailItemDelete(token, params);
				if(result.result === "SUCCESS"){
					if(deleteSelected.count <= itemUpdateCount){
						const item_idx = detail.item_list.findIndex(item => item.item_id === deleteSelected.item_id);
						if(item_idx >= 0) {
							detail.item_list.splice(item_idx, 1);
						}
					}else{
						deleteSelected.count = deleteSelected.count - itemUpdateCount;
					}
				}
				handleModalClose('deleteItem');
				handleModalView('deleteItemComplete');
				break;
			case "deleteComplete":
				handleModalClose('deleteComplete');
				handleModalClose('detail');
				// const idx = dataList.mail_list.findIndex(mail => mail.mail_guid === detail.mail_guid);
				// if(idx >= 0) {
				// 	dataList.mail_list.splice(idx, 1);
				// }
				fetchData(option);
				break;
			case "deleteItemComplete":
				handleModalClose('deleteItemComplete');
				break;
		}
	}

	const ConfirmChild = () => {
		return(
			<InputItem>
				<p>{t('DEL_COUNT_CONFIRM', {count: deleteSelected.count})}</p>
				<TextInput placeholder="수량" type="number" value={itemUpdateCount} onChange={e => handleItemCount(e)} width="200px" />
			</InputItem>
		);
	}

	return (
		loading ? <TableSkeleton count={10}/> :
		<>
			<SelectWrapper>
				<SelectInput
					value={option}
					onChange={e => {
						setOption(e.target.value);
					}}>
					<option value="RECEIVE">받은 우편</option>
					<option value="SEND">보낸 우편</option>
				</SelectInput>
			</SelectWrapper>
			{option === 'RECEIVE' && (
				<>
					{/* <CheckWrapper>
						<CheckBox id="viewDelReceiveMail" label="삭제 우편 보기" />
					</CheckWrapper> */}
					<UserTableWrapper>
						<UserDefaultTable>
							<thead>
								<tr>
									<th width="170">수신일자</th>
									<th width="200">발송자</th>
									<th width="300">우편 제목</th>
									<th width="80">상태</th>
									<th width="100">첨부 아이템</th>
									<th width="80">수령</th>
									<th width="80">시스템 우편</th>
									{/* <th width="170">수령 일자</th> */}
								</tr>
							</thead>
							<tbody>
								{dataList.mail_list &&
									dataList.mail_list.map((mail, idx) => {
										return (
											<tr key={idx}>
												<td>{convertKTC(mail.create_time)}</td>
												<td>{mail.sender_nickname}</td>
												<td>
													<MailLink
														onClick={e => {
															e.preventDefault();
															handleModalView('detail');
															handleDetail(mail.title, mail.content, mail.item_list, mail.mail_guid);
														}}>
														{mail.title}
													</MailLink>
												</td>
												<td>{mail.status === true ? '확인' : '미확인'}</td>
												<td>{mail.item_list.length > 0 ? 'Y' : 'N'}</td>
												<td>{mail.is_get_item === true ? '수령함' : '미수령함'}</td>
												<td>{mail.is_system_mail === true ? 'Y' : 'N'}</td>
												{/* <td>
													{mail.is_get_item_dt && String(new Date(new Date(mail.is_get_item_dt).setHours(new Date(mail.is_get_item_dt).getHours() + 9)).toLocaleString())}
												</td> */}
											</tr>
										);
									})}
							</tbody>
						</UserDefaultTable>
					</UserTableWrapper>
				</>
			)}
			{option === 'SEND' && (
				<>
					{/* <CheckWrapper>
						<CheckBox id="viewDelSendMail" label="삭제 우편 보기" />
					</CheckWrapper> */}
					<UserTableWrapper>
						<UserDefaultTable>
							<thead>
								<tr>
									<th width="170">발송 일자</th>
									<th width="200">수신자</th>
									<th width="300">우편 제목</th>
									<th width="120">첨부 아이템</th>
								</tr>
							</thead>
							<tbody>
								{dataList.mail_list &&
									dataList.mail_list.map((mail, idx) => {
										return (
											<tr key={idx}>
												<td>{convertKTC(mail.create_time)}</td>
												<td>{mail.receiver_nickname}</td>
												<td>
													<MailLink
														onClick={e => {
															e.preventDefault();
															handleModalView('detail');
															handleDetail(mail.title, mail.content, mail.item_list, mail.mail_guid);
														}}>
														{mail.title}
													</MailLink>
												</td>
												<td>{mail.item_list.length > 0 ? 'Y' : 'N'}</td>
											</tr>
										);
									})}
							</tbody>
						</UserDefaultTable>
					</UserTableWrapper>
				</>
			)}
			{/*상세*/}
			<MailDetailModal
				mailModal={modalState.detailModal}
				handleClick={() => handleModalClose('detail')}
				setDetail={setDetail}
				content={detail}
				handleDelete={() => handleModalSubmit('detail')}
				handleItemDelete={(param) => handleModalSubmit('deleteItem', param)}
				authDelete={authDelete}
			/>
			{/*메일 삭제 모달*/}
			<ConfirmModal
				modalText={t('USER_MAIL_DEL_CONFIRM')}
				view={modalState.deleteSubmitModal}
				handleSubmit={() => handleModalSubmit('deleteSubmit')}
				handleCancel={() => handleModalClose('deleteSubmit')}
				handleClose={() => handleModalClose('deleteSubmit')}
			/>
			<CompletedModal
				view={modalState.deleteCompleteModal}
				modalText={t('DEL_COMPLETE')}
				handleComplete={() => handleModalSubmit('deleteComplete')}
			/>
			{/*메일 아이템 삭제 모달*/}
			<CustomConfirmModal
				ChildView={ConfirmChild}
				view={modalState.deleteItemModal}
				handleSubmit={() => handleModalSubmit('deleteItemSubmit')}
				handleCancel={() => handleModalClose('deleteItem')}
				handleClose={() => handleModalClose('deleteItem')}
			/>
			<CompletedModal
				view={modalState.deleteItemCompleteModal}
				modalText={t('DEL_ITEM_COMPLETE')}
				handleComplete={() => handleModalSubmit('deleteItemComplete')}
			/>
		</>
	);
};

export default UserMailInfo;

const UserDefaultTable = styled.table`
	border: 1px solid #e8eaec;
	border-top: 1px solid #000;
	font-size: 14px;
	margin-bottom: 40px;
	th {
		background: #efefef;
		font-weight: 700;
	}
	th,
	td {
		padding: 12px;
		text-align: center;
		border-left: 1px solid #e8eaec;
		vertical-align: middle;
	}
	td {
		background: #fff;
		border-bottom: 1px solid #e8eaec;
		word-break: break-all;
	}
	button {
		height: 24px;
		font-size: 13px;
	}
`;

const QuestTable = styled(UserDefaultTable)`
	tbody {
		td {
			padding: 9px 12px;
		}
	}
`;

const UserTableWrapper = styled.div`
	width: 100%;
	overflow: auto;
	margin-bottom: 40px;
	${UserDefaultTable}, ${QuestTable} {
		margin-bottom: 0;
	}
	&::-webkit-scrollbar {
		height: 4px;
	}
	&::-webkit-scrollbar-thumb {
		background: #666666;
	}
	&::-webkit-scrollbar-track {
		background: #d9d9d9;
	}
`;

const MailLink = styled.div`
	color: #61a2d0;
	text-decoration: underline;
`;

const SelectWrapper = styled.div`
	select {
		height: 30px;
	}
	margin-bottom: 10px;
`;
const CheckWrapper = styled.div`
	text-align: right;
	padding: 10px;
	margin-top: -40px;
	height: 30px;
	margin-bottom: 10px;
	font-size: 14px;
	font-weight: 700;
`;

const InputItem = styled.div`
	display: flex;
    flex-direction: column;
	align-items: center;
    justify-content: center;  /* 수평 중앙 정렬 */
	gap: 10px;
	${TextInput} {
		height: 35px;
		font-size: 14px;
		width: 100px;
        padding: 10px 20px;
	}
`;