import { 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,
} from '../../styles/Components';

import {
	FormGroup, FormHelperText, FormInput, FormLabel,
	FormTextArea, FormTextAreaWrapper, MessageWrapper, FormRowGroup, FormRowInput,
} from '../../styles/ModuleComponents';
import { modalTypes, caliumRequestInitData } from '../../assets/data';
import {DynamicModal, Modal} from '../common';
import { CaliumLimitCount, CaliumRequestRegist } from '../../apis/Calium';

const CaliumRequestRegistModal = ({ registView, setRegistView, userInfo }) => {
	const { t } = useTranslation();
	const token = sessionStorage.getItem('token');

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

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

	const [resultData, setResultData] = useState(caliumRequestInitData);	//데이터 정보
	const [maxCount, setMaxCount] = useState(0)

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

	// 입력 수량 처리
	const handleCount = e => {
		const regex = /^\d*\.?\d{0,2}$/;
		if (!regex.test(e.target.value) && e.target.value !== '-') {
			return;
		}

		let count = 0;
		if (e.target.value === '-0') {
			count = 1;
		} else if (e.target.value < 0) {
			let plusNum = Math.abs(e.target.value);
			count = plusNum;
		} else{
			count = e.target.value;
		}
		setResultData((prevState) => ({
			...prevState,
			count: count,
		}));
	};

	// 입력 글자 제한
	const handleInputData = e => {
		if (e.target.value.length > 100) {
			return;
		}
		setResultData((prevState) => ({
			...prevState,
			content: e.target.value.trimStart(),
		}));
	};

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

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

	const initData = () =>{
		setMaxCount(0);
		setResultData(caliumRequestInitData);
	}

	const handleSubmit = async (type, param = null) => {
		switch (type) {
			case "maxCount":
				setLoading(true);
				await CaliumLimitCount(token, resultData).then(data => {
					setMaxCount(data.reward_total_count);
					setLoading(false);
				}).catch(reason => {
					console.log(reason);
					setLoading(false);
					setAlertMsg(t('SEARCH_LIMIT_FAIL'));
				})
				break;
			case "submit":
				if (!checkCondition()) return;

				handleModalView('registConfirm');
				break;
			case "cancel":
				handleModalView('cancel');
				break;
			case "cancelConfirm":
				initData();
				handleModalClose('cancel');
				setRegistView();
				break;
			case "registConfirm":
				setLoading(true);

				await CaliumRequestRegist(token, resultData).then(data => {
					setLoading(false);
				});

				handleModalClose('registConfirm');
				handleModalView('registComplete');
				break;
			case "registComplete":
				initData();
				handleModalClose('registComplete');
				setRegistView();
				window.location.reload();
				break;
			case "warning":
				setAlertMsg('');
				break;
		}
	}

	const checkCondition = () => {
		return (
			resultData.content !== ''
			&& resultData.count > 0
			&& resultData.dept !== ''
			&& maxCount > 0
			&& resultData.count <= maxCount
		);
	};

	return (
		<>
			<Modal min="760px" $view={registView}>
				<Title $align="center">칼리움 충전 요청 등록</Title>
				<MessageWrapper>
					<FormRowGroup>
						<FormLabel>인출 가능 수량</FormLabel>
						<FormRowInput
							type="text"
							name="maxCount"
							value={maxCount}
							readOnly={true}
						/>
						<Button theme="find" text="조회" handleClick={e => handleSubmit('maxCount')} />
						{maxCount <= 0 &&
							<FormHelperText>
								{t('SEARCH_LIMIT_TOTAL')}
							</FormHelperText>
						}
					</FormRowGroup>


					<FormGroup>
						<FormLabel>부서</FormLabel>
						<FormInput
							type="text"
							name="department"
							placeholder="ex) 사업실 라이브운영팀"
							value={resultData.dept}
							onChange={e => {
								setResultData((prevState) => ({
									...prevState,
									dept: e.target.value.trim(),
								}));
							}}
						/>
					</FormGroup>

					<FormGroup>
						<FormLabel>요청수량</FormLabel>
						<FormInput
							type="number"
							name="count"
							value={resultData.count}
							step={"0.01"}
							min={0}
							onChange={e => handleCount(e)}
						/>
						<FormHelperText>
							{t('LENGTH_NUMBER_POINT_2')}
						</FormHelperText>
					</FormGroup>

					<FormGroup>
						<FormLabel>요청사유</FormLabel>
						<FormTextAreaWrapper>
							<FormTextArea
								name="content"
								value={resultData.content}
								placeholder="요청사유를 입력해주세요."
								onChange={e => handleInputData(e)}
								maxLength={100}
							/>
							<FormHelperText>
								{t('LENGTH_TEXT_LIMIT_100',{count:resultData.content.length})}
							</FormHelperText>
						</FormTextAreaWrapper>
					</FormGroup>
				{isNullValue && <SearchBarAlert $marginTop="25px">{t('REQUIRED_VALUE_CHECK')}</SearchBarAlert>}
				</MessageWrapper>

				<BtnWrapper $gap="10px" $justify="center" $marginTop="20px">
					<Button text="취소" theme="line" handleClick={() => handleSubmit('cancel')} />
					<Button
						type="submit"
						text="등록"
						name="등록버튼"
						theme={
							maxCount > 0 && resultData.content !== '' && resultData.dept !== '' && resultData.count > 0
								? 'primary'
								: 'disable'
						}
						handleClick={() => handleSubmit('submit')}
					/>
				</BtnWrapper>
			</Modal>

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

export default CaliumRequestRegistModal;

