import { styled } from 'styled-components';
import RadioInput from '../../common/input/Radio';
import { useState, useEffect, Fragment } from 'react';
import CheckBox from '../../common/input/CheckBox';

import { Title, SelectInput, BtnWrapper, TextInput, Label, InputLabel, DatePickerWrapper, Textarea, ModalText, ButtonClose, SearchBarAlert } from '../../../styles/Components';
import Button from '../../common/button/Button';
import Modal from '../../common/modal/Modal';

import IconDelete from '../../../assets/img/icon/icon-delete.png';
import CloseIcon from '../../../assets/img/icon/icon-close.png';
import DatePickerComponent from '../../common/Date/DatePickerComponent';
import MailRegistUploadBtn from '../MailRegistUploadBtn';
import { benItems, HourList, MinuteList, modalTypes, wellType } from '../../../assets/data';
import { EventModify, MailModify } from '../../../apis';

import { authList } from '../../../store/authList';
import { useRecoilValue } from 'recoil';
import { convertKTC, convertKTCDate, timeDiffMinute } from '../../../utils';
import { useTranslation } from 'react-i18next';
import DynamicModal from '../../common/modal/DynamicModal';

const MailDetailModal = ({ detailView, handleDetailView, content }) => {
	const userInfo = useRecoilValue(authList);
	const { t } = useTranslation();
	const token = sessionStorage.getItem('token');

	const id = content && content.id;
	const onlyView = userInfo.auth_list && !userInfo.auth_list.some(auth => auth.id === 23);
	const updateAuth = userInfo.auth_list && userInfo.auth_list.some(auth => auth.id === 23);

	const [sendHour, setSendHour] = useState('00');
	const [sendMin, setSendMin] = useState('00');

	const [item, setItem] = useState('');
	const [itemCount, setItemCount] = useState('');
	const [resource, setResource] = useState('19010001');
	const [resourceCount, setResourceCount] = useState('');

	const [modifyModal, setModifyModal] = useState('hidden');
	const [completeModal, setCompleteModal] = useState('hidden');
	const [resultData, setResultData] = useState({});

	const [modalState, setModalState] = useState({
		updateConfirmModal: 'hidden',
		updateCompleteModal: 'hidden',
	});

	const [isNullValue, setIsNullValue] = useState(false);
	// 과거 판단
	const [isPast, setIsPast] = useState(false);
	const [isChanged, setIsChanged] = useState(false);
	const [isItemNullValue, setIsItemNullValue] = useState(false);

	const [excelFile, setExcelFile] = useState(content.target ? content.target : '');
	const [excelName, setExcelName] = useState(null);
	const [downloadData, setDownLoadData] = useState(null);

	const [btnValidation, setBtnValidation] = useState(false);
	const [updateMessage, setUpdateMessage] = useState('수정이 완료되었습니다.');
	const [alertMessage, setAlertMessage] = useState('');
	const [undefinedFile, setUndefinedFile] = useState(false);
	const [disabledBtn, setDisabledBtn] = useState(false); // 예약 발송 확인용
	const [alertMsg, setAlertMsg] = useState('');

	const KOREAN_TIME = content && convertKTCDate(content.send_dt);

	const initialData = {
		send_hour: content && KOREAN_TIME.getHours() < 10 ? '0' + content && KOREAN_TIME.getHours() : content && KOREAN_TIME.getHours(),
		send_min: content && KOREAN_TIME.getMinutes() < 10 ? '0' + content && KOREAN_TIME.getMinutes() : content && KOREAN_TIME.getMinutes(),
		send_status: content && content.send_status,
	};

	useEffect(() => {
		document.querySelector('#fileinput').value = '';

		setResultData({
			is_reserve: content && content.is_reserve,
			send_dt: content && KOREAN_TIME,
			mail_type: content && content.mail_type,
			receive_type: content && content.receive_type,
			user_type: content && content.user_type,
			mail_list: content && content.mail_list,
			item_list: content && content.item_list,
			guid: content && content.target,
		});

		content && content.mail_list.length === 1 && setBtnValidation(true);
		content && content.is_reserve === false && setBtnValidation(true);

		setItem('');
		KOREAN_TIME < new Date ? setIsPast(true) : setIsPast(false);
		setExcelFile(content && content.target);
		setDownLoadData(content && content.target);
		setDisabledBtn(content && content.is_reserve && false);
		
		// 복수 or 단일일 때 content.target을 exel name 으로 지정
		(content && content.receive_type === 'MULTIPLE') ? 
		setExcelName(content && content.target) 
		: setExcelName('')

	}, [content]);

	// console.log('downloadData', downloadData);
	// console.log('isPast', isPast);
	// console.log("guid", resultData.guid)
	// console.log("메일 형식", content && content.receive_type,"   엑셀네임", excelName)

	// 아이템 수량 숫자 체크
	const handleItemCount = e => {
		if (e.target.value === '0' || e.target.value === '-0') {
			setItemCount('1');
			e.target.value = '1';
		} else if (e.target.value < 0) {
			let plusNum = Math.abs(e.target.value);
			setItemCount(plusNum);
		} else {
			setItemCount(e.target.value);
		}
	};

	// 아이템 추가
	const handleItemList = () => {
		if(benItems.includes(item)){
			setAlertMsg(t('MAIL_ITEM_ADD_BEN'))
			return;
		}
		item.length === 0 || itemCount.length === 0 ? setIsItemNullValue(true) : setIsItemNullValue(false);

		if (item.length === '' || itemCount.length === 0 || itemCount <= 0) {
			setIsItemNullValue(true);
		} else if (item.length !== 0) {
			setIsItemNullValue(false);
			setIsChanged(true);

			const newItem = { item: item, item_cnt: itemCount };
			resultData.item_list.push(newItem);

			setItem('');
			setItemCount('');
		}
	};

	// 아이템 삭제
	const onItemRemove = id => {
		let filterList = resultData.item_list && resultData.item_list.filter(item => item !== resultData.item_list[id]);
		setIsChanged(true);

		// console.log('filterList', filterList);

		setResultData({ ...resultData, item_list: filterList });
	};

	// 자원 수량 숫자 체크
	const handleResourceCount = e => {
		if (e.target.value === '0' || e.target.value === '-0') {
			setResourceCount('1');
			e.target.value = '1';
		} else if (e.target.value < 0) {
			let plusNum = Math.abs(e.target.value);
			setResourceCount(plusNum);
		} else {
			setResourceCount(e.target.value);
		}
	};

	// 자원 추가
	const handleResourceList = () => {
		resourceCount.length === 0 ? setIsItemNullValue(true) : setIsItemNullValue(false);

		if (resourceCount.length === 0 || resourceCount <= 0) {
			setIsItemNullValue(true);
		} else {
			setIsItemNullValue(false);
			const name = wellType.find(well => well.value === resource).name;
			const newItem = { item: resource, item_cnt: resourceCount, item_name: name };

			resultData.item_list.push(newItem);
			
			setResourceCount('');
		}
	};

	// 입력창 삭제
	const onLangDelete = language => {
		let filterList = resultData.mail_list && resultData.mail_list.filter(el => el.language !== language);

		if (filterList.length === 1) setBtnValidation(true);

		setIsChanged(true);
		setResultData({ ...resultData, mail_list: filterList });
	};

	// 발송 날짜 세팅 로직
	const handleSelectedDate = data => {
		const sendDate = new Date(data);

		const resultSendData = new Date(sendDate.getFullYear(), sendDate.getMonth(), sendDate.getDate(), sendHour, sendMin);

		setIsChanged(true);
		setResultData({ ...resultData, send_dt: resultSendData });
	};

	// 발송 시간 세팅 로직
	const handleSendTime = e => {
		if (e.target.id === 'hour') setSendHour(e.target.value);
		else if (e.target.id === 'min') setSendMin(e.target.value);

		const sendDate = new Date(resultData.send_dt);
		const result = new Date(sendDate.getFullYear(), sendDate.getMonth(), sendDate.getDate(), e.target.id === 'hour' ? e.target.value : sendHour, e.target.id === 'min' ? e.target.value : sendMin);

		setIsChanged(true);
		setResultData({ ...resultData, send_dt: result });
	};

	// 우편 상세 정보 수정
	const handleModifyModal = () => {
		if (
			resultData.mail_list.map(data => data.content === '' || data.title === '').includes(true) ||
			(resultData.receive_type === 'MULTIPLE' ? excelFile === null : resultData.guid === '') ||
			resultData.send_dt.length === 0 ||
			resultData.mail_type === 'SELECT' ||
			isChanged === false ||
			alertMessage
		) {
			isChanged === true && setIsNullValue(true);
		} else {
			// 복수로 수정하거나 복수로 등록할 때 항상 excel name을 넘겨줘야합니다.
			content && content.receive_type === 'MULTIPLE' ? setResultData({ ...resultData, file_name: excelName === null ? downloadData : excelName }) : setExcelName('');

			// setExcelName(content && content.target)

			setIsNullValue(false);
			if (modifyModal === 'hidden') {
				setModifyModal('view');
			} else {
				setModifyModal('hidden');
			}
		}
	};

	// 상세 정보 단일 체크
	const handleSingleBtn = () => {
		if (content && content.is_reserve === true && !onlyView && !isPast) {
			setResultData({ ...resultData, guid: '' });
			delete resultData.file_name;

			document.querySelector('#fileinput').value = '';

			setExcelFile(null);
			setIsChanged(true);
		}

	};

	// 상세 정보 복수 체크
	const handleMultiBtn = () => {
		if (content && content.is_reserve === true) {
			delete resultData.guid;
		}
		setIsChanged(true);
	};

	// 완료 모달창
	const handleCompleteModal = () => {
		if (completeModal === 'hidden') {
			setCompleteModal('view');
		} else {
			setCompleteModal('hidden');

			window.location.reload();
		}
	};

	// 메일 수정 버튼
	const handleModifyMail = () => {
		
		if(resultData.receive_type === 'MULTIPLE') {
			delete resultData.guid

			MailModify(token, id, resultData);
		} else {
			MailModify(token, id, resultData);
		}

		handleCompleteModal();
		handleModifyModal();
	};

	// 확인 버튼 후 다 초기화
	const handleReset = () => {
		setBtnValidation(false);
		setIsNullValue(false);
		setIsChanged(false);
		setUndefinedFile(false);
		setIsItemNullValue(false);
		setAlertMessage('');
		setExcelFile(null);
		setExcelName(null);
	};

	// 상세 페이지에서 파일 삭제
	const handleDetailDelete = e => {
		e.preventDefault();

		if (content && content.is_reserve === true) {
			setDownLoadData(undefined);
			setUndefinedFile(true);
			setResultData({ ...resultData, guid: '' });
			delete resultData.file_name;

			document.querySelector('#fileinput').value = '';

			setExcelFile(null);
		}

		setIsChanged(true);
	};

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

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

	const handleSubmit = async (type, param = null) => {
		switch (type) {
			case "submit":
				// if (!conditionCheck()) return;

				handleModalView('updateConfirm');
				break;
			case "updateConfirm":
				const timeDiff = timeDiffMinute(resultData.start_dt, (new Date))
				// 이벤트 시작 30분전이나 이미 SystemMail이 add된 상태에서는 수정할 수 없다.
				if(content.add_flag || timeDiff <= 30){
					setAlertMsg(t('EVENT_TIME_LIMIT_UPDATE'));
					handleModalClose('updateConfirm');
					return;
				}
				EventModify(token, id, resultData);
				handleModalClose('updateConfirm');
				handleModalView('updateComplete');
				break;
			case "updateComplete":
				handleModalClose('updateComplete');
				window.location.reload();
				break;
			case "warning":
				setAlertMsg('');
				break;
		}
	}

	return (
		<>
			<Modal min="960px" $view={detailView}>
				<Title $align="center">우편 상세 정보</Title>

				<RegistInfo>
					<span>등록자 : {content && content.create_by}</span>
					<span>등록일 : {content && convertKTC(content.create_dt, false)}</span>
					{content && typeof content.update_by !== 'undefined' && (
						<>
							<span>수정자 : {content && content.update_by}</span>
							<span>수정일 : {content && convertKTC(content.update_dt, false)}</span>
						</>
					)}
				</RegistInfo>
				<ModalWrapper>
					<RegistGroup>
						<InputRow>
							<CheckBox
								label="예약 발송"
								id="reserve"
								checked={resultData && resultData.is_reserve}
								setData={e => {
									setResultData({ ...resultData, is_reserve: e.target.checked });
									setDisabledBtn(e.target.checked);
									setIsChanged(true);
								}}
								disabled={(content && content.is_reserve === false) || onlyView}
							/>
							{content && content.is_reserve === false ? (
								<></>
							) : (
								content &&
								content.is_reserve === true &&
								resultData.is_reserve === true && (
									<InputItem>
										<InputLabel>발송 시간</InputLabel>
										<InputGroup>
											<DatePickerWrapper>
												<DatePickerComponent
													readOnly={(content && content.is_reserve === false) || onlyView || isPast}
													name={initialData.send_dt}
													selectedDate={resultData ? resultData.send_dt : initialData.send_dt}
													handleSelectedDate={data => handleSelectedDate(data)}
													pastDate={new Date()}
												/>
											</DatePickerWrapper>
											<SelectInput
												onChange={e => handleSendTime(e)}
												id="hour"
												disabled={(content && content.is_reserve === false) || onlyView || isPast}
												value={
													resultData && String(new Date(resultData.send_dt).getHours()) < 10
														? '0' + String(new Date(resultData.send_dt).getHours())
														: resultData && String(new Date(resultData.send_dt).getHours())
												}>
												{HourList.map(hour => (
													<option
														value={hour}
														key={hour}
														// selected={
														// 	resultData && String(new Date(resultData.send_dt).getHours()) < 10
														// 		? '0' + String(new Date(resultData.send_dt).getHours()) === hour
														// 		: resultData && String(new Date(resultData.send_dt).getHours()) === hour
														// 		? 'selected'
														// 		: ''
														// }
													>
														{hour}
													</option>
												))}
											</SelectInput>
											<SelectInput
												onChange={e => {
													handleSendTime(e);
													setIsChanged(true);
												}}
												id="min"
												disabled={(content && content.is_reserve === false) || onlyView || isPast}
												value={
													resultData && String(new Date(resultData.send_dt).getMinutes()) < 10
														? '0' + String(new Date(resultData.send_dt).getMinutes())
														: resultData && String(new Date(resultData.send_dt).getMinutes())
												}>
												{MinuteList.map(min => (
													<option
														value={min}
														key={min}
														// selected={
														// 	resultData && String(new Date(resultData.send_dt).getMinutes()) < 10
														// 		? '0' + String(new Date(resultData.send_dt).getMinutes()) === min
														// 		: resultData && String(new Date(resultData.send_dt).getMinutes()) === min
														// 		? 'selected'
														// 		: ''
														// }
													>
														{min}
													</option>
												))}
											</SelectInput>
										</InputGroup>
									</InputItem>
								)
							)}
							<InputItem>
								<InputLabel>우편 타입</InputLabel>
								<SelectInput
									onChange={e => {
										setResultData({ ...resultData, mail_type: e.target.value });
										setIsChanged(true);
									}}
									value={content && resultData.mail_type}
									disabled={(content && content.is_reserve === false) || onlyView || isPast}>
									<option value="SELECT">타입 선택</option>
									<option value="SYSTEM_GUID">시스템 안내</option>
									<option value="INSPECTION_COMPENSATION">점검 보상</option>
									<option value="RECOVER_COMPENSATION">복구 보상</option>
									<option value="EVENT_COMPENSATION">이벤트 보상</option>
								</SelectInput>
							</InputItem>
							<InputItem>
								<InputLabel>발송상태</InputLabel>
								<div>
									{content && initialData.send_status === 'WAIT' && <MailState>대기</MailState>}
									{content && initialData.send_status === 'FINISH' && <MailState result="success">완료</MailState>}
									{content && initialData.send_status === 'FAIL' && <MailState result="fail">실패</MailState>}
								</div>
							</InputItem>
						</InputRow>
						<MailReceiver>
							<InputItem>
								<InputLabel>수신대상</InputLabel>
								<InputItem>
									<SelectInput onChange={e => setResultData({ ...resultData, user_type: e.target.value })} value={resultData.user_type} disabled={(content && content.is_reserve === false) || onlyView || isPast}>
										<option value="GUID">GUID</option>
										<option value="NICKNAME">아바타명</option>
									</SelectInput>
								</InputItem>
								<div>
									<InputGroup>
										<RadioInput
											label="단일"
											id="SINGLE"
											name="receiver"
											value="SINGLE"
											disabled={(content && content.is_reserve === false) || onlyView || isPast}
											fontWeight="600"
											checked={resultData.receive_type === 'SINGLE'}
											handleChange={e => {
												setResultData({ ...resultData, receive_type: e.target.id });
												setIsChanged(true);
											}}
											handleClick={handleSingleBtn}
										/>
										<TextInput
											placeholder={resultData.user_type === "GUID" ? "GUID 입력" : resultData.user_type === "NICKNAME" ? "아바타명 입력" : "이메일 입력"}
											disabled={resultData.receive_type !== 'SINGLE' || (content && content.is_reserve === false) || onlyView || isPast}
											// defaultValue={resultData.receive_type === 'SINGLE' && resultData.guid !== '' ? content.target : ''}
											value={resultData.receive_type === 'SINGLE' && resultData.guid !== '' ? resultData.guid : ''}
											onChange={e => {
												let list = [...resultData.guid];
												list = e.target.value;
												setResultData({ ...resultData, guid: list });
												setIsChanged(true);
											}}
										/>
									</InputGroup>
									{content && resultData.receive_type === 'MULTIPLE' && typeof resultData.guid !== 'undefined' ? (
										<InputGroup>
											<RadioInput
												label="복수"
												id="MULTIPLE"
												name="receiver"
												value="MULTIPLE"
												fontWeight="600"
												checked={content && resultData.receive_type === 'MULTIPLE'}
												disabled
											/>
											<MailRegistUploadBtn
												disabled={resultData.receive_type !== 'MULTIPLE'}
												downloadData={downloadData}
												setResultData={setResultData}
												resultData={resultData}
												handleDetailDelete={handleDetailDelete}
												setExcelFile={setExcelFile}
												alertMessage={alertMessage}
												setAlertMessage={setAlertMessage}
												undefinedFile={undefinedFile}
												disabledBtn={disabledBtn}
												excelName={excelName}
												setExcelName={setExcelName}
												status={initialData.send_status}
											/>
										</InputGroup>
									) : (
										<InputGroup>
											<RadioInput
												label="복수"
												id="MULTIPLE"
												name="receiver"
												value="MULTIPLE"
												fontWeight="600"
												disabled={(content && content.is_reserve === false) || onlyView || isPast}
												handleChange={e => setResultData({ ...resultData, receive_type: e.target.id })}
												handleClick={handleMultiBtn}
											/>
											<MailRegistUploadBtn
												setUpdateMessage={setUpdateMessage}
												disabled={resultData.receive_type !== 'MULTIPLE'}
												setResultData={setResultData}
												resultData={resultData}
												excelFile={excelFile}
												setExcelFile={setExcelFile}
												alertMessage={alertMessage}
												setAlertMessage={setAlertMessage}
												undefinedFile={undefinedFile}
												handleDetailDelete={handleDetailDelete}
												disabledBtn={disabledBtn}
												excelName={excelName}
												setExcelName={setExcelName}
												status={initialData.send_status}
											/>
										</InputGroup>
									)}
								</div>
							</InputItem>
						</MailReceiver>
					</RegistGroup>
					{resultData.mail_list &&
						resultData.mail_list.map(data => {
							return (
								<Fragment key={data.language}>
									<MailRegistBox>
										<LangArea>
											언어 : {data.language}
											{btnValidation === false ? (
												<BtnClose
													onClick={e => {
														e.preventDefault();
														onLangDelete(data.language);
													}}
												/>
											) : (
												<BtnClose opacity="10%" />
											)}
										</LangArea>
										<MailRegistTable>
											<tbody>
												<tr>
													<th width="120">
														<Label>제목</Label>
													</th>
													<td>
														<InputItem>
															<TextInput
																placeholder="우편 제목 입력"
																maxLength="30"
																id={data.language}
																value={data.title}
																readOnly={(content && content.is_reserve === false) || onlyView || isPast}
																onChange={e => {
																	let list = [...resultData.mail_list];
																	let findIndex = resultData.mail_list && resultData.mail_list.findIndex(item => item.language === e.target.id);
																	list[findIndex].title = e.target.value.trimStart();

																	setResultData({ ...resultData, mail_list: list });
																	setIsChanged(true);
																}}
															/>
														</InputItem>
													</td>
												</tr>
												<tr>
													<th>
														<Label>내용</Label>
													</th>
													<td>
														<Textarea
															value={data.content}
															readOnly={(content && content.is_reserve === false) || onlyView || isPast}
															id={data.language}
															onChange={e => {
																if (e.target.value.length > 2000) {
																	return;
																}
																let list = [...resultData.mail_list];
																let findIndex = resultData.mail_list && resultData.mail_list.findIndex(item => item.language === e.target.id);
																list[findIndex].content = e.target.value.trimStart();

																setResultData({ ...resultData, mail_list: list });
																setIsChanged(true);
															}}
														/>
													</td>
												</tr>
											</tbody>
										</MailRegistTable>
									</MailRegistBox>
								</Fragment>
							);
						})}
					<MailRegistBox>
						<MailRegistTable>
							<tbody>
								<tr>
									<th width="120">
										<Label>아이템 첨부</Label>
									</th>
									<td>
										<InputItem>
											<TextInput
												placeholder="Item Meta id 입력"
												value={item}
												onChange={e => {
													let list = [];
													list = e.target.value.trimStart();
													setItem(list);
												}}
												disabled={(content && content.is_reserve === false) || onlyView || isPast}
											/>
											<TextInput
												placeholder="수량"
												value={itemCount}
												type="number"
												onChange={e => handleItemCount(e)}
												width="90px"
												disabled={(content && content.is_reserve === false) || onlyView || isPast}
											/>
											<Button
												text="추가"
												theme={itemCount.length === 0 || item.length === 0 ? 'disable' : 'search'}
												handleClick={handleItemList}
												errorMessage={(content && content.is_reserve === false) || onlyView || isPast}
											/>
										</InputItem>
										{/* {isItemNullValue && <SearchBarAlert $marginTop="15px">필수값을 입력해주세요.</SearchBarAlert>}
										<div>
											{resultData.item_list && (
												<ItemList>
													{content &&
														resultData.item_list.map((data, index) => {
															return (
																<Item key={index}>
																	<span>
																		{data.item}({data.item_cnt})
																	</span>
																	{(content && content.is_reserve === false) || 
																		(updateAuth && <BtnDelete onClick={() => onItemRemove(index)}></BtnDelete>) ||
																		isPast
																	}
																</Item>
															);
														})}
												</ItemList>
											)}
										</div> */}
									</td>
								</tr>
								<tr>
									<th width="120">
										<Label>자원 첨부</Label>
									</th>
									<td>
										<InputItem>
											<SelectInput onChange={e => setResource(e.target.value)} value={resource} disabled={(content && content.is_reserve === false) || onlyView || isPast}>
												{wellType.map((data, index) => (
													<option key={index} value={data.value}>
														{data.name}
													</option>
												))}
											</SelectInput>
											<TextInput placeholder="수량" type="number" value={resourceCount} disabled={(content && content.is_reserve === false) || onlyView || isPast} onChange={e => handleResourceCount(e)} width="200px" />
											<Button text="추가" theme={resourceCount.length === 0 || resource.length === 0 ? 'disable' : 'search'} handleClick={handleResourceList} width="100px" height="35px" errorMessage={(content && content.is_reserve === false) || onlyView || isPast} />
										</InputItem>
										{isItemNullValue && <SearchBarAlert $marginTop="15px">필수값을 입력해주세요.</SearchBarAlert>}

										<div>
											{resultData.item_list && (
												<ItemList>
													{resultData.item_list.map((data, index) => {
														return (
															<Item key={index}>
																<span>
																	{data.item_name}[{data.item}] ({data.item_cnt})
																</span>
																{(content && content.is_reserve === true) || onlyView || isPast && <BtnDelete onClick={() => onItemRemove(index)}></BtnDelete>}
															</Item>
														);
													})}
												</ItemList>
											)}
										</div>
									</td>
								</tr>
							</tbody>
						</MailRegistTable>
					</MailRegistBox>
				</ModalWrapper>
				<BtnWrapper $justify="flex-end" $gap="10px" $paddingTop="20px">
					<Button
						text="확인"
						theme="line"
						name="확인버튼"
						handleClick={() => {
							handleDetailView();
							handleReset();
						}}
					/>
					{(updateAuth && content && content.is_reserve === true) && !isPast && (
						<Button
							type="submit"
							text="수정"
							id="수정버튼"
							theme={
								(content && content.mail_list.map(data => data.content === '' || data.title === '').includes(true)) ||
								(resultData.receive_type === 'MULTIPLE' ? excelFile === null : resultData.guid === '') ||
								resultData.mail_type === 'SELECT' ||
								isChanged === false ||
								alertMessage.length > 1
									? 'disable'
									: 'primary'
							}
							handleClick={() => {
								handleModifyModal();
							}}
						/>
					)}
				</BtnWrapper>
			</Modal>
			{/* 확인 모달 */}
			<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={modifyModal}>
				<BtnWrapper $justify="flex-end">
					<ButtonClose onClick={handleModifyModal} />
				</BtnWrapper>
				<ModalText $align="center">
					우편 정보 수정사항을 <br />
					저장하시겠습니까?
				</ModalText>
				<BtnWrapper $gap="10px">
					<Button text="취소" theme="line" size="large" width="100%" handleClick={handleModifyModal} />
					<Button text="확인" theme="primary" type="submit" size="large" width="100%" handleClick={handleModifyMail} />
				</BtnWrapper>
			</Modal>
			{/* 완료 모달 */}
			<Modal min="440px" $padding="40px" $bgcolor="transparent" $view={completeModal}>
				<BtnWrapper $justify="flex-end">
					<ButtonClose onClick={handleCompleteModal} />
				</BtnWrapper>
				<ModalText $align="center">수정이 완료되었습니다. </ModalText>
				<BtnWrapper $gap="10px">
					<Button text="확인" theme="primary" type="submit" size="large" width="100%" handleClick={handleCompleteModal} />
				</BtnWrapper>
			</Modal>
			{/* 경고 모달 */}
			<DynamicModal
				modalType={modalTypes.completed}
				view={alertMsg ? 'view' : 'hidden'}
				modalText={alertMsg}
				handleSubmit={() => handleSubmit('warning')}
			/>
		</>
	);
};

export default MailDetailModal;

const InputItem = styled.div`
	display: flex;
	align-items: center;
	gap: 20px;
	${TextInput},${SelectInput} {
		height: 35px;
		font-size: 14px;
	}
	${TextInput} {
		padding: 0 15px;
	}
	${SelectInput} {
		width: max-content;
	}
`;

const ModalWrapper = styled.div`
	max-height: 70vh;
	padding-bottom: 5px;
	overflow: auto;
	&::-webkit-scrollbar {
		width: 4px;
	}
	&::-webkit-scrollbar-thumb {
		background: #666666;
	}
	&::-webkit-scrollbar-track {
		background: #d9d9d9;
	}
`;

const RegistInfo = styled.div`
	display: flex;
	justify-content: flex-end;
	gap: 50px;
	font-size: 14px;
	margin-bottom: 10px;
`;

const BtnClose = styled.button`
	width: 16px;
	height: 16px;
	background: url(${CloseIcon}) 50% 50% no-repeat;
	position: absolute;
	top: 50%;
	transform: translate(0, -50%);
	right: 20px;
	opacity: ${props => props.opacity};
`;

const LangArea = styled.div`
	background: #f9f9f9;
	padding: 10px 20px;
	font-size: 14px;
	font-weight: 600;
	position: relative;
`;

const MailRegistBox = styled.div`
	margin-bottom: 20px;
	border-top: 1px solid #999;
	border-bottom: 1px solid #999;
`;

const MailRegistTable = styled.table`
	th,
	td {
		padding: 15px 0;
	}
	td {
		${TextInput} {
			max-width: 600px;
		}
		${Textarea} {
			width: 100%;
			border: 1px solid #d9d9d9;
			border-radius: 5px;
			height: 150px;
			padding: 15px;
			&:focus {
				border: 1px solid #2c2c2c;
			}
		}
	}
`;

const RegistGroup = styled.div`
	display: flex;
	width: 100%;
	flex-flow: column;
	gap: 20px;
	padding: 20px;
	border-top: 1px solid #000;
	border-bottom: 1px solid #000;
	font-size: 14px;
	margin-bottom: 40px;
`;

const InputRow = styled.div`
	display: flex;
	flex-wrap: wrap;
	gap: 20px 50px;
`;

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

const MailReceiver = styled.div`
	display: flex;
	align-items: flex-start;
	${InputItem} {
		align-items: flex-start;
	}
	${InputLabel} {
		line-height: 35px;
	}
	${TextInput} {
		margin-left: 20px;
		width: 400px;
	}
	${InputGroup} {
		margin-bottom: 5px;
	}
`;

const MailState = styled.span`
	font-weight: 600;
	color: ${props => (props.result === 'success' ? '#08994B' : props.result === 'fail' ? '#ff0000' : '#2c2c2c')};
`;

const ItemList = styled.ul`
	display: flex;
	gap: 20px;
	padding: 10px 20px;
	flex-wrap: wrap;
`;

const Item = styled.li`
	display: flex;
	gap: 5px;
	align-items: center;
`;

const BtnDelete = styled.button`
	width: 12px;
	height: 12px;
	background: url(${IconDelete}) 50% 50% no-repeat;
`;
