import { useState, Fragment, useEffect } from 'react';
import Button from '../../components/common/button/Button';
import Loading from '../../components/common/Loading';

import {
	Title,
	BtnWrapper,
	TextInput,
	SelectInput,
	Label,
	InputLabel,
	Textarea,
	SearchBarAlert,
} from '../../styles/Components';

import { useNavigate } from 'react-router-dom';
import { EventIsItem, EventSingleRegist } from '../../apis';

import { authList } from '../../store/authList';
import { useRecoilValue } from 'recoil';
import { useTranslation } from 'react-i18next';
import {
	AppendRegistBox, AppendRegistTable, AreaBtnClose,
	BtnDelete,
	Item,
	ItemList, LangArea, ModalInputItem, ModalItem, ModalItemList, ModalSubText, RegistGroup,
	RegistInputItem,
	RegistInputRow, RegistNotice, RegistTable,
} from '../../styles/ModuleComponents';
import AuthModal from '../../components/common/modal/AuthModal';
import { authType, benItems, modalTypes, wellType } from '../../assets/data';
import DynamicModal from '../../components/common/modal/DynamicModal';
import DateTimeInput from '../../components/common/input/DateTimeInput';
import { timeDiffMinute } from '../../utils';

const EventRegist = () => {
	const navigate = useNavigate();
	const userInfo = useRecoilValue(authList);
	const { t } = useTranslation();
	const token = sessionStorage.getItem('token');

	const [loading, setLoading] = useState(false);		// 로딩 창
	const [modalState, setModalState] = useState({
		cancelModal: 'hidden',
		registConfirmModal: 'hidden',
		registCompleteModal: 'hidden',
	});		// 모달 관리

	const [item, setItem] = useState('');		// 아이템 값
	const [itemCount, setItemCount] = useState('');		// 아이템 개수
	const [resource, setResource] = useState('19010001');	// 자원 값
	const [resourceCount, setResourceCount] = useState('');		// 자원 개수

	const [isNullValue, setIsNullValue] = useState(false);		// 데이터 값 체크
	const [btnValidation, setBtnValidation] = useState(false);		// 입력창 버튼
	const [itemCheckMsg, setItemCheckMsg] = useState('');
	const [alertMsg, setAlertMsg] = useState('');

	const [time, setTime] = useState({
		start_hour: '00',
		start_min: '00',
		end_hour: '00',
		end_min: '00',
	});	//시간 정보

	const [resultData, setResultData] = useState({
		is_reserve: false,
		start_dt: '',
		end_dt: '',
		event_type: 'ATTD',
		mail_list: [
			{
				title: '',
				content: '',
				language: 'KO',
			},
			{
				title: '',
				content: '',
				language: 'EN',
			},
			{
				title: '',
				content: '',
				language: 'JA',
			}
		],
		item_list: [],
		guid: '',
	});	//데이터 정보

	useEffect(() => {
		if (checkCondition()) {
			setIsNullValue(false);
		} else {
			setIsNullValue(true);
		}
	}, [resultData]);

	useEffect(() => {
		setItemCheckMsg('');
	}, [item]);

	const combineDateTime = (date, hour, min) => {
		if (!date) return null;
		return new Date(date.getFullYear(), date.getMonth(), date.getDate(), hour, min);
	};

	// 날짜 처리
	const handleDateChange = (data, type) => {
		const date = new Date(data);
		setResultData({
			...resultData,
			[`${type}_dt`]: combineDateTime(date, time[`${type}_hour`], time[`${type}_min`]),
		});
	};

	// 시간 처리
	const handleTimeChange = (e, type) => {
		const { id, value } = e.target;
		const newTime = { ...time, [`${type}_${id}`]: value };
		setTime(newTime);

		const date = resultData[`${type}_dt`] ? resultData[`${type}_dt`] : new Date();

		setResultData({
			...resultData,
			[`${type}_dt`]: combineDateTime(date, newTime[`${type}_hour`], newTime[`${type}_min`]),
		});
	};

	// 아이템 수량 숫자 체크
	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 = async () => {
		if(benItems.includes(item)){
			setAlertMsg(t('MAIL_ITEM_ADD_BEN'))
			return;
		}
		if(item.length === 0 || itemCount.length === 0) return;

		const token = sessionStorage.getItem('token');
		const result = await EventIsItem(token, {item: item});

		if(result.data.result === "ERROR"){
			setItemCheckMsg(t('NOT_ITEM'));
			return;
		}

		const itemIndex = resultData.item_list.findIndex((data) => data.item === item);
		if (itemIndex !== -1) {
			setItemCheckMsg(t('MAIL_ITEM_ADD_DUPL'));
			return;
		}
		const newItem = { item: item, item_cnt: itemCount, item_name: result.data.data.item_info.item_name };

		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]);
		setResultData({ ...resultData, item_list: filterList });
	};

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

		if (filterList.length === 1) {
			setBtnValidation(true);
		} else {
			setBtnValidation(false);
		}

		setResultData({ ...resultData, mail_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 = (e) => {
		if(resource.length === 0 || resourceCount.length === 0) return;

		const itemIndex = resultData.item_list.findIndex(
			(item) => item.item === resource
		);

		if (itemIndex !== -1) {
			const item_cnt = resultData.item_list[itemIndex].item_cnt;
			resultData.item_list[itemIndex].item_cnt = Number(item_cnt) + Number(resourceCount);
		} else {
			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 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 (!checkCondition()) return;
				const timeDiff = timeDiffMinute(resultData.start_dt, (new Date))
				if(timeDiff < 60) {
					setAlertMsg(t('EVENT_TIME_LIMIT_ADD'));
					return;
				}

				handleModalView('registConfirm');
				break;
			case "cancel":

				handleModalView('deleteSubmit');
				break;
			case "registConfirm":
				setLoading(true);

				const result = await EventSingleRegist(token, resultData);

				setLoading(false);
				handleModalClose('registConfirm');
				handleModalView('registComplete');
				break;
			case "registComplete":
				handleModalClose('registComplete');

				navigate('/servicemanage/event');
				break;
			case "warning":
				setAlertMsg('');
				break;
		}
	}

	const checkCondition = () => {
		return (
			resultData.mail_list.every(data => data.content !== '' && data.title !== '') &&
			(resultData.start_dt.length !== 0) &&
			(resultData.end_dt.length !== 0)
		);
	};

	return (
		<>
			{userInfo.auth_list && !userInfo.auth_list.some(auth => auth.id === authType.eventUpdate) ? (
				<AuthModal/>
			) : (
				<>
					<Title>이벤트 등록</Title>
					<RegistGroup>
						<RegistInputRow>
							<RegistInputItem>
								<InputLabel>이벤트 타입</InputLabel>
								<SelectInput onChange={e => setResultData({ ...resultData, event_type: e.target.value })} value={resultData.event_type}>
									<option value="ATTD">출석 이벤트</option>
								</SelectInput>
							</RegistInputItem>
							<DateTimeInput
								title="시작 시간"
								dateName="시작 일자"
								selectedDate={resultData.start_dt}
								handleSelectedDate={data => handleDateChange(data, 'start')}
								onChange={e => handleTimeChange(e, 'start')}
							/>
							<DateTimeInput
								title="종료 시간"
								dateName="종료 일자"
								selectedDate={resultData.end_dt}
								handleSelectedDate={data => handleDateChange(data, 'end')}
								onChange={e => handleTimeChange(e, 'end')}
							/>
						</RegistInputRow>
					</RegistGroup>
					{resultData.mail_list.map((data, idx) => {
						return (
							<Fragment key={idx}>
								<AppendRegistBox>
									<LangArea>
										언어 : {data.language}
										{btnValidation === false ? (
											<AreaBtnClose
												onClick={e => {
													e.preventDefault();
													onLangDelete(data.language);
												}}
											/>
										) : (
											<AreaBtnClose opacity="10%" />
										)}
									</LangArea>
									<RegistTable>
										<tbody>
											<tr>
												<th width="120">
													<Label>제목</Label>
												</th>
												<td>
													<RegistInputItem>
														<TextInput
															placeholder="우편 제목 입력"
															maxLength="30"
															id={data.language}
															value={data.title}
															onChange={e => {
																if (e.target.value.length > 30) {
																	return;
																}
																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 });
															}}
														/>
													</RegistInputItem>
													<RegistNotice $color={data.title.length > 29 ? 'red' : '#666'}>* 최대 등록 가능 글자수 ({data.title.length}/30자)</RegistNotice>
												</td>
											</tr>
											<tr>
												<th>
													<Label>내용</Label>
												</th>
												<td>
													<Textarea
														maxLength="2000"
														value={data.content}
														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 });
														}}
													/>
													<RegistNotice $color={data.content.length > 1999 ? 'red' : '#666'}>* 최대 등록 가능 글자수 ({data.content.length}/2000자)</RegistNotice>
												</td>
											</tr>
										</tbody>
									</RegistTable>
								</AppendRegistBox>
							</Fragment>
						);
					})}

					<AppendRegistBox>
						<AppendRegistTable>
							<tbody>
								<tr>
									<th width="120">
										<Label>아이템 첨부</Label>
									</th>
									<td>
										<RegistInputItem>
											<TextInput placeholder="Item Meta id 입력" value={item} onChange={e => setItem(e.target.value.trimStart())} />
											<TextInput placeholder="수량" type="number" value={itemCount} onChange={e => handleItemCount(e)} width="100px" />
											<Button text="추가" theme={itemCount.length === 0 || item.length === 0 ? 'disable' : 'search'} handleClick={handleItemList} width="100px" height="35px" />
											{itemCheckMsg && <SearchBarAlert>{itemCheckMsg}</SearchBarAlert>}
										</RegistInputItem>
									</td>
								</tr>
								<tr>
									<th width="120">
										<Label>자원 첨부</Label>
									</th>
									<td>
										<RegistInputItem>
											<SelectInput onChange={e => setResource(e.target.value)} value={resource}>
												{wellType.map((data, index) => (
													<option key={index} value={data.value}>
														{data.name}
													</option>
												))}
											</SelectInput>
											<TextInput placeholder="수량" type="number" value={resourceCount} onChange={e => handleResourceCount(e)} width="200px" />
											<Button text="추가" theme={resourceCount.length === 0 || resource.length === 0 ? 'disable' : 'search'} handleClick={handleResourceList} width="100px" height="35px" />
										</RegistInputItem>

										<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>
																<BtnDelete onClick={() => onItemRemove(index)}></BtnDelete>
															</Item>
														);
													})}
												</ItemList>
											)}
										</div>
									</td>
								</tr>
							</tbody>
						</AppendRegistTable>
					</AppendRegistBox>
					{isNullValue && (
						<SearchBarAlert $align="right" $padding="0 0 15px">
							{t('NULL_MSG')}
						</SearchBarAlert>
					)}

					<BtnWrapper $justify="flex-end" $gap="10px">
						<Button text="취소" theme="line" handleClick={() => handleModalView('cancel')} />
						<Button
							type="submit"
							text="등록"
							theme={checkCondition() ? 'primary' : 'disable'}
							handleClick={() => handleSubmit('submit')}
						/>
					</BtnWrapper>

					{/* 등록 모달 */}
					<DynamicModal
						modalType={modalTypes.confirmOkCancel}
						view={modalState.registConfirmModal}
						modalText={t('EVENT_REGIST_CONFIRM')}
						handleSubmit={() => handleSubmit('registConfirm')}
						handleCancel={() => handleModalClose('registConfirm')}
					/>
					<DynamicModal
						modalType={modalTypes.childOkCancel}
						view={modalState.registConfirmModal}
						handleCancel={() => handleModalClose('registConfirm')}
						handleSubmit={() => handleSubmit('registConfirm')}
					>
						<ModalItem>
							{t('EVENT_REGIST_CONFIRM')}
							{resultData.item_list && (
								<ModalItemList>
									{resultData.item_list.map((data, index) => {
										return (
											<Item key={index}>
												<span>
													{data.item_name} {data.item_cnt.toLocaleString()}
												</span>
											</Item>
										);
									})}
								</ModalItemList>
							)}
						</ModalItem>
					</DynamicModal>
					{/* 완료 모달 */}
					<DynamicModal
						modalType={modalTypes.completed}
						view={modalState.registCompleteModal}
						modalText={t('REGIST_COMPLTE')}
						handleSubmit={() => handleSubmit('registComplete')}
					/>
					{/* 취소 모달 */}
					<DynamicModal
						modalType={modalTypes.confirmOkCancel}
						view={modalState.cancelModal}
						modalText={t('EVENT_REGIST_CANCEL')}
						handleCancel={() => handleModalClose('cancel')}
						handleSubmit={() => handleSubmit('cancel')}
					/>
					{/* 경고 모달 */}
					<DynamicModal
						modalType={modalTypes.completed}
						view={alertMsg ? 'view' : 'hidden'}
						modalText={alertMsg}
						handleSubmit={() => handleSubmit('warning')}
					/>
					{loading && <Loading/>}
				</>
			)}
		</>
	);
};

export default EventRegist;

