import React, { useState, Fragment, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import Button from '../../common/button/Button';
import Loading from '../../common/Loading';

import {
	Title,
	BtnWrapper,
	SearchBarAlert, SelectInput,
} from '../../../styles/Components';

import {
	FormInput,
	FormLabel,
	MessageWrapper,
	FormRowGroup,
	FormStatusBar,
	FormStatusLabel,
	FormStatusWarning,
	FormButtonContainer, FormGroup, FormItemGroup, SubText,
} from '../../../styles/ModuleComponents';
import { modalTypes } from '../../../assets/data';
import { DynamicModal, Modal, SingleDatePicker, SingleTimePicker } from '../../common';
import { NONE, TYPE_MODIFY, TYPE_REGISTRY } from '../../../assets/data/adminConstants';
import { useModal } from '../../../utils/hook';
import { convertKTCDate } from '../../../utils';
import { BattleEventModify, BattleEventSingleRegist } from '../../../apis/Battle';
import { battleEventStatusType } from '../../../assets/data/types';
import { isValidDayRange } from '../../../utils/date';
import CheckBox from '../../common/input/CheckBox';
import { LandOwnedChangesRegist, LandOwnerChangesDelete, UserInfoView } from '../../../apis';

const OwnerChangeModal = ({ modalType, detailView, handleDetailView, content, setDetailData }) => {
	const { t } = useTranslation();
	const token = sessionStorage.getItem('token');

	const [loading, setLoading] = useState(false);		// 로딩 창
	const {
		modalState,
		handleModalView,
		handleModalClose
	} = useModal({
		cancel: 'hidden',
		registConfirm: 'hidden',
		registComplete: 'hidden'
	});

	const [isNullValue, setIsNullValue] = useState(false);		// 데이터 값 체크
	const [alertMsg, setAlertMsg] = useState('');

	const [resultData, setResultData] = useState(initData);	//데이터 정보

	useEffect(() => {
		if(content && Object.keys(content).length > 0){
			const ownerChanges = content.owner_changes;
			let changes_info;
			if(ownerChanges && ownerChanges.length > 0){
				changes_info = ownerChanges.filter(item => item.status === 'WAIT').reduce((maxItem, current) => {
					return (!maxItem || current.id > maxItem.id ) ? current : maxItem;
				}, null);
			}
			setResultData({
				...resultData,
				land_id: content.land_id,
				land_name: content.land_name,
				building_id: content.building_id,
				building_name: content.building_name,
				is_reserve: changes_info?.is_reserve || false,
				reservation_dt: (changes_info && convertKTCDate(changes_info.reservation_dt)) || new Date(),
				user_guid: changes_info?.user_guid || '',
				user_name: changes_info?.user_name || '',
				id: changes_info?.id || null
			});
		}
	}, [modalType, content]);

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

	// 날짜 변경 핸들러
	const handleStartDateChange = (date) => {
		if (!date) return;

		const newDate = new Date(date);

		setResultData(prev => ({
			...prev,
			reservation_dt: newDate
		}));
	};

	// 시간 변경 핸들러
	const handleStartTimeChange = (time) => {
		if (!time) return;

		const newDateTime = resultData.reservation_dt
			? new Date(resultData.reservation_dt)
			: new Date();

		newDateTime.setHours(
			time.getHours(),
			time.getMinutes(),
			0,
			0
		);

		setResultData(prev => ({
			...prev,
			reservation_dt: newDateTime
		}));
	};

	const handleReset = () => {
		setDetailData({});
		setResultData(initData);
		handleDetailView();
	}

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

				handleModalView('registConfirm');
				break;
			case "cancel":
				handleModalView('cancel');
				break;
			case "cancelConfirm":
				handleModalClose('cancel');
				handleReset();
				break;
			case "user":
				if(isView()) return;
				const guid = resultData.user_guid;
				if(!guid || guid.length !== 32){
					setAlertMsg(t('WARNING_GUID_CHECK'))
					return;
				}
				setLoading(true);
				await UserInfoView(token, guid).then(data => {
					setLoading(false);
					if(Object.keys(data).length === 0){
						setAlertMsg(t('WARNING_GUID_CHECK'));
						setResultData({ ...resultData, user_name: '' })
						return;
					}
					const nickname = data.char_info.character_name;
					setResultData({ ...resultData, user_name: nickname })
				}).catch(reason => {
					setAlertMsg(t('API_FAIL'));
				});
				break;
			case "registConfirm":
				setLoading(true);

				if(isView()){
					console.log(resultData);
					setLoading(false);
					handleModalClose('registConfirm');

					const resvDt = resultData.reservation_dt;
					const now = new Date();
					if(resvDt < now){
						setAlertMsg(t('LAND_OWNED_CHANGES_DELETE_TIME_WARNING'));
						handleReset();
						return;
					}

					await LandOwnerChangesDelete(token, resultData).then(data => {
						setLoading(false);
						handleModalClose('registConfirm');
						if(data.result === "SUCCESS") {
							handleModalView('registComplete');
						}else if(data.result === "ERROR_LAND_OWNER_CHANGES_RESERVATION"){
							setAlertMsg(t('LAND_OWNED_CHANGES_DELETE_STATUS_WARNING'));
						}else{
							setAlertMsg(t('DELETE_FAIL'));
						}
					}).catch(reason => {
						setAlertMsg(t('API_FAIL'));
					});
				}else{
					await LandOwnedChangesRegist(token, resultData).then(data => {
						setLoading(false);
						handleModalClose('registConfirm');
						if(data.result === "SUCCESS") {
							handleModalView('registComplete');
						}else if(data.result === "GUID_CHECK"){
							setAlertMsg(t('WARNING_GUID_CHECK'));
						}else{
							setAlertMsg(t('REGIST_FAIL'));
						}
					}).catch(reason => {
						setAlertMsg(t('API_FAIL'));
					});
				}

				break;
			case "registComplete":
				handleModalClose('registComplete');
				handleReset();
				break;
			case "warning":
				setAlertMsg('');
				break;
		}
	}

	const checkCondition = () => {
		return (
			resultData.land_id !== ''
			&& resultData.land_name !== ''
			&& resultData.user_guid !== ''
			&& resultData.user_name !== ''
			&& (!resultData.is_reserve || (resultData.is_reserve && resultData.reservation_dt !== ''))
		);
	};

	const isView = (label) => {
		switch (label) {
			case "modify":
				return modalType === TYPE_MODIFY;
			case "registry":
				return modalType === TYPE_REGISTRY;
			case "reservation_dt":
			case "user":
				return modalType === TYPE_REGISTRY || (modalType === TYPE_MODIFY &&resultData?.id === null);
			default:
				return modalType === TYPE_MODIFY && resultData?.id !== null;
		}
	}

	return (
		<>
			<Modal min="760px" $view={detailView}>
				<Title $align="center">소유권 변경</Title>
				<MessageWrapper>
					<FormRowGroup>
						<FormItemGroup>
							<CheckBox
								label="예약"
								id="reserve"
								checked={resultData.is_reserve}
								setData={e => setResultData({ ...resultData, is_reserve: e.target.checked, reservation_dt: new Date() })}
								disabled={!isView('user')}
							/>
						</FormItemGroup>
						{resultData.is_reserve && (
							<>
								<SingleDatePicker
									label="발송시간"
									disabled={!isView('reservation_dt')}
									dateLabel="발송 일자"
									onDateChange={handleStartDateChange}
									selectedDate={resultData?.reservation_dt}
								/>
								<SingleTimePicker
									disabled={!isView('reservation_dt')}
									selectedTime={resultData?.reservation_dt}
									onTimeChange={handleStartTimeChange}
								/>
							</>
						)}

					</FormRowGroup>
					<FormRowGroup><SubText>* 예약 발송 미선택 시 등록과 함께 우편이 즉시 발송됩니다.</SubText></FormRowGroup>
					<FormRowGroup>
						<FormLabel>변경 랜드</FormLabel>
						<FormInput
							type="text"
							width='150px'
							value={resultData?.land_id}
							readOnly={true}
							handleClick={() => handleSubmit('user')}
							disabled={!isView('user')}
						/>
						<FormInput
							type="text"
							width='250px'
							value={resultData?.land_name}
							readOnly={true}
							handleClick={() => handleSubmit('user')}
							disabled={!isView('user')}
						/>
					</FormRowGroup>
					<FormRowGroup>
						<FormLabel>수신 대상</FormLabel>
						<FormInput
							type="text"
							placeholder="guid 입력"
							width='300px'
							value={resultData?.user_guid}
							onChange={e => setResultData({ ...resultData, user_guid: e.target.value })}
							disabled={!isView('user')}
						/>
						<Button
							text="확인"
							theme={!isView() ? 'primary' : 'disable'}
							type="submit"
							size="large"
							width="100px"
							handleClick={() => handleSubmit('user')}
						/>
					</FormRowGroup>
					<FormRowGroup>
						<FormLabel>캐릭터명</FormLabel>
						<FormInput
							type="text"
							width='300px'
							value={resultData?.user_name}
							readOnly={true}
							disabled={!isView('user')}
						/>
					</FormRowGroup>
					{!isView() && isNullValue && <SearchBarAlert $marginTop="25px" $align="right">{t('REQUIRED_VALUE_CHECK')}</SearchBarAlert>}
				</MessageWrapper>

				<BtnWrapper $gap="10px" $marginTop="10px" $marginBottom="20px">
					<FormButtonContainer $gap="10px">
						<>
							<Button text="취소" theme="line" handleClick={() => handleSubmit('cancel')} />
							<Button
								type="submit"
								text={isView() ? "예약 삭제": "등록"}
								name={isView() ? "삭제버튼": "등록버튼"}
								theme={
									checkCondition()
										? 'primary'
										: 'disable'
								}
								handleClick={() => handleSubmit('submit')}
							/>
						</>
					</FormButtonContainer>
				</BtnWrapper>
			</Modal>

			{/* 확인 모달 */}
			<DynamicModal
				modalType={modalTypes.confirmOkCancel}
				view={modalState.registConfirmModal}
				modalText={isView() ? t('LAND_OWNED_CHANGES_SELECT_DELETE') : t('LAND_OWNED_CHANGES_REGIST_CONFIRM')}
				handleSubmit={() => handleSubmit('registConfirm')}
				handleCancel={() => handleModalClose('registConfirm')}
			/>
			{/* 완료 모달 */}
			<DynamicModal
				modalType={modalTypes.completed}
				view={modalState.registCompleteModal}
				modalText={isView() ? t('CANCEL_COMPLETED') : t('REGIST_COMPLTE')}
				handleSubmit={() => handleSubmit('registComplete')}
			/>
			{/* 취소 모달 */}
			<DynamicModal
				modalType={modalTypes.confirmOkCancel}
				view={modalState.cancelModal}
				modalText={t('CANCEL_CONFIRM')}
				handleCancel={() => handleModalClose('cancel')}
				handleSubmit={() => handleSubmit('cancelConfirm')}
			/>
			{/* 경고 모달 */}
			<DynamicModal
				modalType={modalTypes.completed}
				view={alertMsg ? 'view' : 'hidden'}
				modalText={alertMsg}
				handleSubmit={() => handleSubmit('warning')}
			/>
			{loading && <Loading/>}
		</>
	);
};

export const initData = {
	is_reserve: false,
	land_id: '',
	land_name: '',
	user_guid: '',
	user_name: '',
	reservation_dt: ''
}

export default OwnerChangeModal;

