import React, { useState } from 'react';
import {
	JDmodal,
	IUseModal,
	JDbutton,
	JDsingleUploader,
	useFilesManager,
	useInput,
	JDdoc,
	JDdocHeader,
	JDdocSection,
	InputText,
	autoHypen,
	toast,
	onCompletedMessage,
	JDalign
} from '@janda-com/front';
import { lang as LANG } from '../lang/langFn';
import { JDtypho } from '../atom/typho';
import { useMutation } from '@apollo/client';
import { SENDER_CREATE } from '../apollo/queries';
import { senderCreate, senderCreateVariables } from '../types/api';
import client from '../apollo/apolloClient';
import { ISmsConfig } from '../app';
import { LabelValue } from '../atom/LabelValue';

export interface SenderRegistModalProp {
	modalHook: IUseModal;
}

export interface IProps extends SenderRegistModalProp {
	config: ISmsConfig;
}



export const SenderRegistModal: React.FC<IProps> = ({ modalHook }) => {
	const [step, setStep] = useState<'submit' | 'check'>('submit');
	const fileUploaderHook = useFilesManager();
	const nameHook = useInput('');
	const phoneNumberHook = useInput('');
	const file = fileUploaderHook.localFiles[0];
	const [SenderCreateMu, { loading }] = useMutation<senderCreate, senderCreateVariables>(SENDER_CREATE, {
		client,
		variables: {
			input: {
				name: nameHook.value,
				phoneNumber: phoneNumberHook.value,
				files: [
					{
						// TODO TALK 이거 맞는지? 제데로 안올라가든데
						// err "[TypeError] file.createReadStream is not a function"
						upload: new File([file?.base64], file?.fileName, { type: file?.mimeType })
					}
				]
			}
		},
		onCompleted: ({ SenderCreate }) => {
			console.log(SenderCreate);
			onCompletedMessage(SenderCreate, LANG('senderRequested'), LANG('senderRequestedFail'));
			if (SenderCreate.ok) {
				setStep('check');
			}
		}
	});

	const isSubmit = step === 'submit';

	const validater = () => {
		if (!nameHook.value) {
			$('.senderRegistModal__name').focus();
			toast.warn('plz_enter_name');
			return false;
		}
		if (!phoneNumberHook.value) {
			$('.senderRegistModal__number').focus();
			toast.warn('plz_enter_number');
			return false;
		}
		if (!file) {
			$('.senderRegistModal__file').focus();
			toast.warn('plz_enter_file');
			return false;
		}
		return true;
	};

	const handleCreateBtn = () => {
		if (validater()) SenderCreateMu();
	};

	const checkFoot = (
		<JDalign flex={{
			end: true
		}}>
			<JDbutton
				thema="primary"
				onClick={() => {
					modalHook.closeModal();
				}}
				mode="flat"
				label={LANG('confirm')}
			/>
		</JDalign>
	);

	const foot = isSubmit ? undefined : checkFoot;

	return (
		<JDmodal
			className="senderRegistModal"
			loading={loading}
			foot={foot}
			head={{
				title: LANG('senderModalHeader')
			}}
			{...modalHook}
		>
			{isSubmit ? (
				<JDdoc className="senderRegistModal__doc">
					<div style={{
						paddingTop: "1rem"
					}}>
						<JDdocHeader>업소 번호로 문자 발신하기</JDdocHeader>
					</div>
					<JDdocSection>
						{`SMS 발신번호에 발신자 번호를 기입 하시려면 발신자 번호 등록 신청을 하셔야합니다.`}
						<br />
						{`발신자 번호로 등록하시려면 `}
						<JDtypho
							hover
							weight={600}
							color="point"
							onClick={() => {
								window.open('http://admin.tongtongtong.co.kr/ADMIN/solution/sms_certPhone_info.asp');
							}}
						>
							통신가입 사실 증명원
						</JDtypho>{' '}
						을 제출 하셔야 합니다.<br /> 등록소요기간은{' '}
						<JDtypho weight={600} color="point">
							7일
						</JDtypho>{' '}
						정도 입니다, 처리기간 동안 잔다의 발신자 번호로 발신이 가능합니다.<br /> 발신자 등록 인증기간동안 관리번호가 문자 하단에 자동 기입됩니다.
					</JDdocSection>
					<div>
						<div>
							<InputText
								className="senderRegistModal__name"
								require
								label={LANG('senderName')}
								{...nameHook}
							/>
						</div>
						<div>
							<InputText
								className="senderRegistModal__number"
								require
								hyphen
								label={LANG('sendNumber')}
								{...phoneNumberHook}
							/>
						</div>
						<JDsingleUploader
							buttonProps={{
								mode: 'border',
								label: LANG('upload_file')
							}}
							inputProps={{
								className: 'senderRegistModal__file'
							}}
							labelProp={{
								txt: LANG('telecommunication_subscription_proof'),
								require: true
							}}
							fileUploaderHook={fileUploaderHook}
						/>
					</div>
					<JDbutton
						onClick={() => {
							handleCreateBtn();
						}}
						size="long"
						thema="primary"
						mode="flat"
						label={LANG('regist')}
					/>
				</JDdoc>
			) : (
					<JDdoc className="senderRegistModal__doc">
						<JDdocHeader>{LANG('isRegisted')(autoHypen(phoneNumberHook.value))}</JDdocHeader>
						<JDalign mb="large">{LANG('checkRegist')}</JDalign>
						<div>
							<LabelValue mb="normal" label={LANG('senderName')} value={nameHook.value} />
							<LabelValue mb="normal" label={LANG('sendNumber')} value={phoneNumberHook.value} />
							<LabelValue label={LANG('telecommunication_subscription_proof')} value={file?.fileName || ""} />
						</div>
					</JDdoc>
				)}
		</JDmodal>
	);
};

export default SenderRegistModal;
