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

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

import {
	FormGroup, FormHelperText, FormInput, FormLabel,
	FormTextArea, FormTextAreaWrapper, MessageWrapper, FormRowGroup, FormRowInput,
} from '../../styles/ModuleComponents';
import { caliumRequestInitData } from '../../assets/data';
import { Modal} from '../common';
import { CaliumLimitCount, CaliumRequestRegist } from '../../apis/Calium';
import { useAlert } from '../../context/AlertProvider';
import { useLoading } from '../../context/LoadingProvider';
import { alertTypes } from '../../assets/data/types';

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

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

	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 handleReset = () =>{
		setMaxCount(0);
		setResultData(caliumRequestInitData);
		setRegistView();
	}

	const handleSubmit = async (type, param = null) => {
		switch (type) {
			case "maxCount":
				await withLoading(async () => {
					return await CaliumLimitCount(token, resultData);
				}).then(data => {
					setMaxCount(data.reward_total_count);
				}).catch(reason => {
					showToast('SEARCH_LIMIT_FAIL', {type: alertTypes.error})
				});
				break;
			case "submit":
				if (!checkCondition()) return;

				showModal('CALIUM_REGIST_CONFIRM',{
					type: alertTypes.confirm,
					onConfirm: () => handleSubmit('registConfirm')
				})
				break;

			case "registConfirm":
				await withLoading(async () => {
					return await CaliumRequestRegist(token, resultData);
				}).then(data => {
					showToast('CALIUM_REGIST_COMPLTE', {type: alertTypes.success});
				}).catch(error => {
					showToast('API_FAIL', {type: alertTypes.error});
				}).finally(() => {
					handleReset();
				});
				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={() => showModal('CANCEL_CONFIRM', {
							type: alertTypes.confirm,
							onConfirm: () => handleReset()
						})}
					/>
					<Button
						type="submit"
						text="등록"
						name="등록버튼"
						theme={
							maxCount > 0 && resultData.content !== '' && resultData.dept !== '' && resultData.count > 0
								? 'primary'
								: 'disable'
						}
						handleClick={() => handleSubmit('submit')}
					/>
				</BtnWrapper>
			</Modal>

		</>
	);
};

export default CaliumRequestRegistModal;

