import { useState, Fragment, useEffect } from 'react';

import styled from 'styled-components';

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 { authType, ivenTabType, opMailType } from '../../assets/data';
import { useRecoilValue } from 'recoil';
import { authList } from '../../store/authList';
import { convertKTC } from '../../utils';
import { TableSkeleton } from '../Skeleton/TableSkeleton';
import {  opPickupType, opReadType, opYNType } from '../../assets/data/options';
import { useDynamoDBPagination, useModal } from '../../hooks/hook';
import { DynamoPagination } from '../common';

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

	// 받은 우편, 보낸 우편
	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 {
		modalState,
		handleModalView,
		handleModalClose
	} = useModal({
		detail: 'hidden',
		deleteItem: 'hidden',
		deleteSubmit: 'hidden',
		deleteComplete: 'hidden',
		deleteItemComplete: 'hidden'
	});

	const fetchMailData = async (page, startKey) => {
		const params = {
			mail_type: option,
			guid: userInfo.guid,
			page_key: startKey
		};
		return await UserMailView(token, params);
	};

	const {
		data: dataList,
		loading,
		pagination,
		fetchPage,
		goToNextPage,
		goToPrevPage,
		resetPagination
	} = useDynamoDBPagination(fetchMailData);

	useEffect(() => {
		resetPagination();
		fetchPage(1);
	}, [option]);

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

	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 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);
				// }
				fetchPage(pagination.currentPage);
				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}/> :
		<>
			<SelectContainer>
				<SelectInput
					value={option}
					onChange={e => {
						setOption(e.target.value);
					}}>
					{opMailType.map((data, index) => (
						<option key={index} value={data.value}>
							{data.name}
						</option>
					))}
				</SelectInput>

				<DynamoPagination
					pagination={pagination}
					onNextPage={goToNextPage}
					onPrevPage={goToPrevPage}
				/>
			</SelectContainer>

			{option === 'RECEIVE' && (
				<>
					<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?.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>{opReadType.find(type => type.value === mail.status).name}</td>
												<td>{opYNType.find(type => type.value === (mail.item_list.length > 0)).name}</td>
												<td>{opPickupType.find(type => type.value === mail.is_get_item).name}</td>
												<td>{opYNType.find(type => type.value === mail.is_system_mail).name}</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' && (
				<>
					<UserTableWrapper>
						<UserDefaultTable>
							<thead>
								<tr>
									<th width="170">발송 일자</th>
									<th width="200">수신자</th>
									<th width="300">우편 제목</th>
									<th width="120">첨부 아이템</th>
								</tr>
							</thead>
							<tbody>
								{dataList  && 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;
    cursor: pointer;
`;

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;
	}
`;

const SelectContainer = styled.div`
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 10px;
	
	select {
		height: 30px;
	}
`;

const PaginationButtons = styled.div`
	display: flex;
	align-items: center;
	gap: 10px;
`;

const PaginationButton = styled.button`
    background-color: ${props => props.disabled ? '#e0e0e0' : '#6c7eb7'};
    color: ${props => props.disabled ? '#a0a0a0' : 'white'};
    border: none;
    padding: 6px 12px;
    border-radius: 4px;
    font-size: 12px;
    cursor: ${props => props.disabled ? 'not-allowed' : 'pointer'};
    transition: background-color 0.2s;

    &:hover {
        background-color: ${props => props.disabled ? '#e0e0e0' : '#5a6a9b'};
    }
`;

const PageInfo = styled.div`
    font-size: 12px;
    font-weight: 500;
    color: #666;
`;