"use client"
import useResponsive from "@/hooks/useResponsive";
import { APP_URL, DURATION_MAP, IMAGE_PATH, LAYOUT_SETTING, PATTERNS, PaymentMethod } from "@/lib/appConstant";
import { getBodySetting, getCompanyDomain, getContentDetailSetting, getLayoutViewPage, getServicePath, getViewSettings } from "@/lib/redux/features/serviceAdmin";
import { useAppDispatch, useAppSelector } from "@/lib/redux/hooks";
import StorageHelper from "@/lib/storeHelper";
import { CardDataUpdateType, STORAGE_KEYS } from "@/types/common";
import { ServiceViewSettings } from "@/types/serviceAdmin";
import moment from "moment";
import { useTranslations } from "next-intl";
import { useParams, useRouter } from "next/navigation";
import { Fragment, useEffect, useRef, useState } from "react";
import CircularProgress from "@mui/material/CircularProgress";
import { makeStyles } from "tss-react/mui";
import { addTax10, formatThousandsNumber, getUserTrace, handleGMOPayment, handleVeritransPayment, tax10 } from "@/lib/utils";
import { Col, Row, Skeleton } from "antd";
import { FormItem, FormWrapper } from "../ui/form";
import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import Stepper from "@mui/material/Stepper";
import Step from "@mui/material/Step";
import StepLabel from "@mui/material/StepLabel";
import InputFieldButtonRight from "../ui/input/input-field-button-right";
import { CircleCheck, CreditCard } from "lucide-react";
import AppInput from "../ui/input/input";
import { createOrderReceive, getIsPaymentError, getIsPaymentSuccess, getIsRediectUrl, getRediectUrl, gmoCharge, resetCreateOrderReceive, resetCreateOrderReceiveVeritrans, resetPaymentError, setCacheCouponCode, setCacheSubscriptionId, veritransCreateOrderReceive } from "@/lib/redux/features/payment";
import { getAuthInfo } from "@/lib/redux/features/auth";
import { fetchSubscriptionDetail, getIsSubscriptionDetailLoad, getSubscriptionDetail } from "@/lib/redux/features/subscription";
import { fetchCouponUser, getCouponUserDetail, getCouponUserDetailLoad } from "@/lib/redux/features/coupon";
import { showToast } from "../toast/showToast";
import InputUpdateCard from "../ui/input/input-update-card";
import AppButton from "../ui/button/app-button";
import AppLoading from "../ui/loading";
import InputField from "../ui/input/input-field";

type PropsType = { viewSettings?: ServiceViewSettings };
type MakeStylesType = {
    below768: boolean;
    isMegreLayout: boolean;
    styleBody: any;
    subscriptionDetail: any;
};
const day = 1000 * 60 * 60 * 24;



const useStyle = makeStyles<MakeStylesType>()(
    (theme, { below768, isMegreLayout, styleBody, subscriptionDetail }) => ({
        contentImage: {
            marginBottom: '0.5rem',
            marginRight: '0.5rem',
            position: 'relative',
            overflow: below768 ? 'initial' : 'hidden',
            height: '100%',
            // border: '1px solid #d0d0d0',
            '& img': {
                maxHeight: below768 ? 180 : 300,
                maxWidth: below768 ? '100%' : 300,
                objectFit: 'contain',
                minWidth: below768 ? 120 : 180
            },
            display: !below768 ? 'flex' : 'flex',
            width: !below768 ? '100%' : '100%',
            justifyContent: 'center',
            alignItems: 'flex-start'
        },
        imageSubscription: {
            objectFit: 'contain',
            height: '100%',
            width: '100%'
        },
        progressBar: {
            margin: below768 || isMegreLayout ? '0' : '0 5%',
            width: below768 || isMegreLayout ? '100%' : '90%',
            backgroundColor: styleBody.backgroundColor,
            '& .MuiStep-horizontal': !isMegreLayout ? {} : {
                paddingLeft: 0,
                paddingRight: 0
            }
        },
        contents: {
            margin: isMegreLayout ? 0 : '0 5%',
            width: isMegreLayout ? '' : '90%',
            justifyContent: `${!subscriptionDetail.description ? 'center' : ''}`
        },
        notPadding: {
            padding: '0 !important'
        }
    }
));
export default function OrderEntry (props: PropsType) {
    const {
    //   paymentActions: {
    //     resetPaymentError,
    //     gmoCharge,
    //     createOrderReceive,
    //     setCacheCouponCode,
    //     setCacheSubscriptionId,
    //     resetCreateOrderReceive,
    //     veritransCreateOrderReceive,
    //     resetCreateOrderReceiveVeritrans
    //   }
    } = props;
    const t = useTranslations("");
    const dispatch = useAppDispatch();
    const router = useRouter();
    const { below768, getBelow768 } = useResponsive();
    const params = useParams();
    const creditCardRef = useRef<RefType>(null);
  
    const style = useAppSelector(getContentDetailSetting);
    const styleBody = useAppSelector(getBodySetting);
    const layoutViewPage = useAppSelector(getLayoutViewPage);
    const isCreateOrderReceive = useAppSelector((state) => state.payment.isCreateOrderReceive);
    const isVerify = useAppSelector((state) => state.payment.isVerify);
    const isLoadFail = useAppSelector((state) => state.subscriptionsPlan.isLoadFail);
    const urlVeritransPayment = useAppSelector(state => state.payment.redirectUrlVeritrans);
    const isRedirectUrlVeritrans = useAppSelector(state => state.payment.isRedirectUrlVeritrans);
    const servicePath = useAppSelector(getServicePath);
    const currentDomain = useAppSelector(getCompanyDomain);

    const subscriptionDetail = useAppSelector(getSubscriptionDetail);
    const isSubscriptionDetailLoad = useAppSelector(getIsSubscriptionDetailLoad);
    const authUser = useAppSelector(getAuthInfo) || {} as any;
    const isPaymentError = useAppSelector(getIsPaymentError);
    const couponUserDetail = useAppSelector(getCouponUserDetail);
    const isCouponUserDetailLoad = useAppSelector(getCouponUserDetailLoad);
    const viewSettings = useAppSelector(getViewSettings);
    const isPaymentSuccess = useAppSelector(getIsPaymentSuccess);
    const isRediectUrl = useAppSelector(getIsRediectUrl);
    const urlGakkenPayment = useAppSelector(getRediectUrl);

    

    

    // const [cardNumber, setCardNumber] = useState<any>('');
    // const [expiry, setExpiry] = useState<any>('');
    // const [cvc, setCvc] = useState<any>('');
    
    const [isApplyCoupon, setIsApplyCoupon] = useState(false);
    const [couponCode, setCouponCode] = useState<any>(null);
    const [isUpdateCard, setIsUpdateCard] = useState(false);
    const [isLoading, setIsLoading] = useState(false);
    const [couponCodeTemp, setCouponCodeTemp] = useState<any>(null);
    const [isValidCard, setIsValidCard] = useState(true);
    const [initValues, setInitValues] = useState<any>({
        name: '',
        contentGroups: '',
        discount: '',
        duration: '',
        price: '',
        codeCoupon: '',
        discountPrice: '¥0',
        numberFreeTerm: '',
        usagePeriod: '',
        nextPaymentDate: '',
        priceRoot: '',
        netPrice: '',
        taxPrice: '',
        totalPayment: '',
        createdDate: null,
        expiredDate: null,
        cardHolderEmail: '',
        cardHolderName: ''
    });
  
    const [isVerifyLoading, setIsVerifyLoading] = useState(false);
    const [isHtml, setIsHtml] = useState(false);
    const [isLoadCreateOrderReceive, setIsLoadCreateOrderReceive] = useState(false);
    const [cardData, setCardData] = useState<CardDataUpdateType>({
        cvc: '',
        expiry: '',
        cardNumber: '',
        focus: ''
    });
  
    const isMegreLayout = layoutViewPage === LAYOUT_SETTING.HOME_LAYOUT_AND_SEARCH_LAYOUT.id;
    const subscriptionId = params.subscriptionId as string;
    const isGMOPayment = viewSettings.paymentGateway === PaymentMethod.GMO;
    const isGakkenPayment = viewSettings.paymentGateway === PaymentMethod.GAKKEN_ID;
    const cacheCouponCode = StorageHelper.getSessionItem(STORAGE_KEYS.couponCode);
    const cacheGakkenRedirectUrl = StorageHelper.getSessionItem(STORAGE_KEYS.redirectUrlCallback);
    const cacheSubscriptionId = StorageHelper.getSessionItem(STORAGE_KEYS.subsId);
    const userStore = !servicePath || servicePath === '' ? currentDomain : servicePath;
    const isAuthen = StorageHelper.getLocalObject(userStore);
    const isToken = StorageHelper.getCookie(userStore);

    const pathname = `/order-entry/${subscriptionId}`;
  
    const Style: any = {
        spin: {
            height: !below768 ? '100%' : '90%',
            width: '100%',
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            zIndex: '1000',
            position: !below768 ? 'relative' : 'absolute'
        },
        discountPrice: {
            color: 'red'
        },
        selectPaymentMethod: {
            display: 'flex',
            flexDirection: 'column'
            // alignItems: 'flex-end',
            // justifyContent: 'flex-end'
        },
        selectPaymentMethodFormGroup: {
            // display: 'flex',
            // justifyContent: 'flex-end'
            padding: '0 20px',
            marginTop: 10
        },
        containerTitle: {
            padding: isMegreLayout ? '20px 0 0 0' : (!below768 ? '20px 0 0 50px' : '20px 0 0 20px')
        },
        containerCenter: {
            width: '100%',
            display: 'flex',
            justifyContent: 'center',
            backgroundColor: styleBody.backgroundColor || ''
        },
        rowInfo: {
            margin: '12px 0'
        }
    };
  
    const { classes } = useStyle({ below768, isMegreLayout, styleBody, subscriptionDetail });
  
    // const validationSchema = Yup.object().shape({
    //   cardHolderName: Yup.string()
    //     .required(Util.translate('validate.required'))
    //     .matches(PATTERNS.BLANK_SPACES, {
    //       message: Util.translate('validate.blankSpaces')
    //     })
    //     .min(2, Util.translate('validate.min_length_2'))
    //     .max(64, Util.translate('validate.max_length_64')),
    //   cardHolderEmail: Yup.string().trim()
    //     .max(255, Util.translate('validate.max_length_255'))
    //     .required(Util.translate('validate.required'))
    //     .matches(PATTERNS.EMAIL_PATTERN, {
    //       message: Util.translate('validate.email.invalid')
    //     })
    // });
  
    const scrollToTop = () => {
        window.scrollTo({ top: 0, left: 0, behavior: 'smooth' });
    };
    const handleUpdateCard = () => {
        setIsUpdateCard(!isUpdateCard);
        if (!isUpdateCard) {
            setCardData({
                cvc: '',
                expiry: '',
                cardNumber: '',
                focus: ''
            });
            setIsValidCard(true);
        }
    };



    useEffect(() => {
        scrollToTop();
    }, []);
    useEffect(() => {
        subscriptionId && dispatch(fetchSubscriptionDetail(subscriptionId));
    }, [subscriptionId, isToken]);
  
    useEffect(() => {
        if (!isToken && !isAuthen) {
            
            // router.push('/');
        }
    }, [isAuthen, isToken]);
  
    useEffect(() => {
        if (isLoadFail) {
            // router.push('/');
        }
    }, [isLoadFail]);
  
    useEffect(() => {
        if (urlVeritransPayment) {
            if (urlVeritransPayment === 'ok') {
                router.push(`${servicePath ? '/'+servicePath : ''}/thank-you`);
                dispatch(resetCreateOrderReceiveVeritrans());
                StorageHelper.removeSessionItem(STORAGE_KEYS.subsId);
            } else {
                if (isRedirectUrlVeritrans) {
                    window.open(`${urlVeritransPayment}`, '_self');
                } else {
                    setIsLoading(false);
                    dispatch(resetCreateOrderReceiveVeritrans());
                }
            }
      }
      if (!isRedirectUrlVeritrans && urlVeritransPayment === '') {
        setIsLoading(false);
        dispatch(resetCreateOrderReceiveVeritrans());
      }
    }, [urlVeritransPayment, isRedirectUrlVeritrans]);
  
    useEffect(() => {
        if (subscriptionDetail && subscriptionDetail.id) {
            if (subscriptionDetail.isRegistered) {
                // router.push('/');
            }
            const { coupon } = subscriptionDetail;
            const { subscriptionContentGroups } = subscriptionDetail;
            const now = new Date().getTime();
            const usagePeriod = `${moment.utc(now).local().format('YYYY/MM/DD').toString()} - ${subscriptionDetail.numberFreeTerm > 0 ? moment.utc(now + (day * (subscriptionDetail.numberFreeTerm))).local().format('YYYY/MM/DD').toString() : moment.utc(now + (day * (subscriptionDetail.duration))).local().format('YYYY/MM/DD').toString()} `;
            setInitValues({
                name: subscriptionDetail.name,
                numberFreeTerm: subscriptionDetail.numberFreeTerm,
                usagePeriod: `${usagePeriod} ${(subscriptionDetail.numberFreeTerm > 0) ? '(' + t('label.freePeriod') + ')' : ''}`,
                nextPaymentDate: subscriptionDetail.numberFreeTerm > 0 ? moment.utc(now + (day * (subscriptionDetail.numberFreeTerm))).local().format('YYYY/MM/DD').toString() : moment.utc(now + (day * (subscriptionDetail.duration))).local().format('YYYY/MM/DD').toString(),
                contentGroups: subscriptionContentGroups.map((x: any) => x.contentGroupName).join(', '),
                duration: subscriptionDetail.duration + ' ' + t(`subscription.${DURATION_MAP.get(0)}`),
                price: '¥' + formatThousandsNumber(addTax10(subscriptionDetail.discountPrice)),
                priceWithoutTax: '¥' + formatThousandsNumber(subscriptionDetail.discountPrice),
                priceRoot: '¥' + formatThousandsNumber(subscriptionDetail.price),
                netPrice: '¥' + formatThousandsNumber(subscriptionDetail.discountPrice),
                taxPrice: '¥' + formatThousandsNumber(tax10(subscriptionDetail.discountPrice)),
                codeCoupon: coupon ? coupon.name : '',
                totalPayment: '¥' + formatThousandsNumber(addTax10(subscriptionDetail.discountPrice)),
                discountPrice: '¥0',
                createdDate: subscriptionDetail.createdDate ? moment.utc(subscriptionDetail.createdDate).local().format('YYYY/MM/DD').toString() : null,
                expiredDate: subscriptionDetail.expiredDate ? moment.utc(subscriptionDetail.expiredDate).local().format('YYYY/MM/DD').toString() : null,
                cardHolderEmail: authUser.email ? authUser.email : '',
                cardHolderName: ''
            }); 
        }
    }, [subscriptionDetail]);
    useEffect(() => {
        if (isPaymentError) {
            dispatch(resetPaymentError());
        }
    }, [isPaymentError]);
    useEffect(() => {
        if (couponUserDetail && couponCodeTemp) {
            setIsApplyCoupon(true);
            const discountPrice = Math.round(couponUserDetail.couponType === 0 
                ? subscriptionDetail.discountPrice * Number(couponUserDetail.percentage / 100.0) 
                : (couponUserDetail.currency > subscriptionDetail.discountPrice ? subscriptionDetail.discountPrice : couponUserDetail.currency));
            const netPrice = subscriptionDetail.discountPrice - discountPrice;
            const total = subscriptionDetail.discountPrice - discountPrice;
            setCouponCode(couponCodeTemp);
            setInitValues({
                ...initValues,
                codeCoupon: couponCodeTemp,
                discountPrice: '¥' + formatThousandsNumber(discountPrice),
                netPrice: '¥' + formatThousandsNumber(netPrice),
                taxPrice: '¥' + formatThousandsNumber(tax10(netPrice)),
                totalPayment: '¥' + formatThousandsNumber(addTax10(total))
            });
        } else {
            setIsApplyCoupon(false);
        }
    }, [couponUserDetail]);

    useEffect(() => {
        if (isPaymentSuccess) {
            router.push(`${servicePath ? '/'+servicePath : ''}/thank-you`);
        }
    }, [isPaymentSuccess]);
  
    useEffect(() => {
        if (urlGakkenPayment) {
            setIsLoadCreateOrderReceive(false);
            if (isRediectUrl) {
                window.open(`${urlGakkenPayment}`, '_self');
            } else {
                dispatch(resetCreateOrderReceive());
                setIsLoading(false);
            }
        }
        if (!isCreateOrderReceive && urlGakkenPayment === '') {
            setIsLoadCreateOrderReceive(false);
            setIsLoading(false);
        }
    }, [urlGakkenPayment, isCreateOrderReceive]);

  
    const handleErrorPayment = _errorMessage => {
        if (_errorMessage) {
            showToast('error', _errorMessage);
            setIsLoading(false);
        }
    };
  
    const onCancel = () => {
        // setShowPayment(false);
        dispatch(resetCreateOrderReceive());
        router.push(`${servicePath ? '/'+servicePath : ''}/subscription/${subscriptionId}`);
    };

    const handleGmoCharge = (data: any) => {
        dispatch(gmoCharge(data));
    }

    const handleVeritransCreateOrderReceive = (data: any) => {
        dispatch(veritransCreateOrderReceive(data));
    }
  
    const onSubmit = async data => {
        setIsLoading(true);
        const params = {
            ...data,
            subscriptionPlanId: subscriptionId,
            authUser
        };
        if (isGMOPayment) {
            // cardNumber, cardExpire, securityCode, couponCode
            const errorMessage = handleGMOPayment(params, handleGmoCharge, handleErrorPayment);
            if (errorMessage) {
                showToast('error', errorMessage);
            }
            setIsLoading(false);
        } else if (isGakkenPayment) {
            if (cacheCouponCode) {
                StorageHelper.removeSessionItem(STORAGE_KEYS.couponCode);
            }
            if (cacheSubscriptionId) {
                StorageHelper.removeSessionItem(STORAGE_KEYS.subsId);
            }
            if (cacheGakkenRedirectUrl) {
                StorageHelper.removeSessionItem(STORAGE_KEYS.redirectUrlCallback);
            }
            const requestOrderReceive = {
                ...params,
                state: pathname,
                redirectUrl: `${window.location.origin}/${servicePath ? `${servicePath}/` : ''}gakken-payment/processing`
            }
            dispatch(createOrderReceive(requestOrderReceive));
            if (data.couponCode) {
                dispatch(setCacheCouponCode(data.couponCode));
            }
            dispatch(setCacheSubscriptionId(subscriptionId));
        } else {
            setIsLoading(true);
            const userTrace = await getUserTrace();
            const ip = userTrace.ip;
            if (cacheCouponCode) {
                StorageHelper.removeSessionItem(STORAGE_KEYS.couponCode);
            }
            if (cacheSubscriptionId) {
                StorageHelper.removeSessionItem(STORAGE_KEYS.subsId);
            }
            if (data.couponCode) {
                dispatch(setCacheCouponCode(data.couponCode));
            }
            if (data.isHaveCard) {
                const redirectUrl = `${window.location.origin}/${servicePath ? `${servicePath}/` : ''}veritrans-payment/confirm`;
                
                dispatch(setCacheSubscriptionId(subscriptionId));
                dispatch(veritransCreateOrderReceive({
                    redirectUrl: redirectUrl,
                    customerIp: ip,
                    cardHolderEmail: data.cardHolderEmail,
                    cardHolderName: data.cardHolderName,
                    subscriptionPlanId: subscriptionId,
                    couponCode: couponCode,
                    isClose: data.totalPayment === '¥0',
                    state: pathname
                }));
            } else {
                dispatch(setCacheSubscriptionId(subscriptionId));
                const errorMessage = await handleVeritransPayment({
                    ...params,
                    url: `${window.location.origin}/${servicePath ? `${servicePath}/` : ''}veritrans-payment/confirm`,
                    state: pathname,
                    customerIp: ip
                }, handleVeritransCreateOrderReceive);
                if (errorMessage) {
                    showToast('error', errorMessage);
                    setIsLoading(false);
                }
            }
    
            // setIsLoading(false);
        }
    };
  
    const submit = (data: any) => {
        creditCardRef.current?.markTouched();
        if (viewSettings.paymentGateway === PaymentMethod.GAKKEN_ID) {
            // setIsOpenClose(false);
            onSubmit({
            id: subscriptionDetail.id,
            couponCode: couponCode,
            isClose: data.totalPayment === '¥0'
            });
            setIsLoading(true);
        } else {
            if (!authUser.cardNumber || isUpdateCard) {
                // isValidCard
                
                if (isValidCard) {
                    if (cardData.cardNumber.length === 0 || cardData.cvc.length === 0 || cardData.expiry.length === 0) {
                        showToast('error', t('toast.error.creditCardEmpty'));
                    } else {
                        const request = {
                            cardNumber: cardData.cardNumber.replaceAll(' ', ''),
                            cardExpire: cardData.expiry.replaceAll(' ', ''),
                            securityCode: cardData.cvc,
                            tokenApiKey: authUser.tokenApiKey,
                            lang: authUser.lang,
                            cardHolderEmail: data.cardHolderEmail,
                            cardHolderName: data.cardHolderName
                        };
                        onSubmit && onSubmit({
                            ...request,
                            couponCode
                        });
                        setIsLoading(true);
                    }
                } else {
                    showToast('error', t('api.error.841'));
                }
            } else {
                // setIsOpenClose(false);
                onSubmit({
                    isHaveCard: true,
                    id: subscriptionDetail.id,
                    couponCode: couponCode,
                    isClose: data.totalPayment === '¥0',
                    cardHolderEmail: data.cardHolderEmail,
                    cardHolderName: data.cardHolderName
                });
                setIsLoading(true);
            }
        }
    };
    const completePaymentCheck = () => {
        setIsHtml(false);
        setIsUpdateCard(false);
        setIsVerifyLoading(false);
        // setIsOpenClose(true);
        setCardData({
            cvc: '',
            expiry: '',
            cardNumber: '',
            focus: ''
        });
        // completePayment();
    };
    const returnNumberFreePeriod = _days => {
      return `${t('number.day', { days: _days })}`;
    };
    const steps = [t('label.orderEntry'), t('label.orderComplete')];
    if (viewSettings.paymentGateway === PaymentMethod.GAKKEN_ID || viewSettings.paymentGateway === PaymentMethod.VERITRANS) {
      steps.splice(1, 0, t('label.confirmOrder'));
    }

    const validationSchema = {
        cardHolderEmail: z.string()
        .regex(PATTERNS.EMAIL_PATTERN, {
            message: t('validate.email.invalid')
        })
        .min(1, t('validate.required'))
        .max(64, t('validate.max_length_64')),
        cardHolderName: z.string()
                .min(2, t('validate.min_length_2'))
                .max(255, t('validate.max_length_255')),
    }
    const formSchema = z
        .object({
            cardHolderEmail: viewSettings.paymentGateway === PaymentMethod.VERITRANS ? validationSchema.cardHolderEmail : z.string(),
            cardHolderName: viewSettings.paymentGateway === PaymentMethod.VERITRANS ? validationSchema.cardHolderName : z.string(),
            name: z.string(),
            contentGroups: z.string(),
            discount: z.any(),
            duration: z.string(),
            price: z.string(),
            codeCoupon: z.string(),
            discountPrice: z.string(),
            numberFreeTerm: z.any(),
            usagePeriod: z.string(),
            nextPaymentDate: z.string(),
            priceRoot: z.string(),
            netPrice: z.string(),
            taxPrice: z.string(),
            totalPayment: z.string(),
            createdDate: z.string(),
            expiredDate: z.any(),
            priceWithoutTax: z.string(),
        });
    
    type OrderEntryFormSchema = z.infer<typeof formSchema>;
    

    const orderEntryForm = useForm<OrderEntryFormSchema>({
        resolver: zodResolver(formSchema),
        defaultValues: { ...initValues }
    });
    console.log('errors: ', orderEntryForm.formState.errors);
    console.log('errors: ', orderEntryForm.formState.errors);
    
    const values = orderEntryForm.getValues();

    useEffect(() => {
        if (initValues) {
            orderEntryForm.reset(initValues);
        }
    }, [initValues]);

    if (isLoading) {
        return (
            <Fragment>
                <div style={isHtml ? { width: '100%', height: isVerifyLoading ? '80vh' : '30vh' } : { width: '0', height: '0' }}>
                    <iframe id='iframe' style={{ width: '100%', height: '100%' }} frameBorder={'0'} allowFullScreen={true} />
                </div>
                <div style={Style.spin}>
                    <AppLoading/>
                </div>
            </Fragment>
        )
    }

    return (
        <Fragment>
            <div style={isHtml ? { width: '100%', height: isVerifyLoading ? '80vh' : '30vh' } : { width: '0', height: '0' }}>
                <iframe id='iframe' style={{ width: '100%', height: '100%' }} frameBorder={'0'} allowFullScreen={true} />
            </div>
            
            {
                isHtml
                ? <Fragment>
                    {
                        !isVerifyLoading &&
                        <div className="text-right">
                            <AppButton
                                className="btn btn-info text-right"
                                // variant="contained"
                                onClick={completePaymentCheck}
                            >
                                {t('button.ok')}
                            </AppButton>
                        </div>
                    }
                </Fragment>
                : <FormWrapper<OrderEntryFormSchema>
                    form={orderEntryForm}
                    onSubmit={submit}
                    layout="vertical"
                    className="space-y-4 w-full"
                >
                    {
                        <div style={{ width: '100%', padding: isMegreLayout ? '0 20.8px' : '' }}>
                            <Row className={`${classes.progressBar}`}>
                                <Col span={24} style={Style.containerTitle}>
                                    {
                                        isMegreLayout
                                        ? <h4 style={{ fontWeight: 400, fontSize: 18, lineHeight: '18px', color: '#595757' }}>{t('title.orderProcedure')}</h4>
                                        : <h4 style={{ fontWeight: 700 }}>{t('title.orderProcedure')}</h4>
                                    }
                                </Col>
                                <Col span={24} style={Style.containerCenter}>
                                    <div style={{ width: '100%' }}>
                                        <Stepper activeStep={0} style={{ backgroundColor: styleBody.backgroundColor ? styleBody.backgroundColor : '', padding: isMegreLayout ? '24px 0' : (!below768 ? '24px' : '0 px') }} alternativeLabel={!!below768}>
                                        {steps.map((text, index) => {
                                            return (
                                            <Step key={index}>
                                                {
                                                isMegreLayout
                                                    ? <StepLabel><span style={{ fontFamily: 'Noto Sans JP', fontSize: '13px', fontWeight: 400, lineHeight: '18.82px' }}>{text}</span></StepLabel>
                                                    : <StepLabel>{text}</StepLabel>
                                                }
                                            </Step>
                                            );
                                        })}
                                        </Stepper>
                                    </div>
                                </Col>
                            </Row>
                            {
                                (isSubscriptionDetailLoad || isLoadCreateOrderReceive)
                                ? <div className="flex items-center justify-center w-full mt-5">
                                    <div>
                                        <Row>
                                            <Col span={24}><Skeleton className={'skeleton-input-component'} /></Col>
                                            <Col sm={24} md={12}><Skeleton className={'skeleton-input-component'} /></Col>
                                            <Col sm={24} md={12}><Skeleton className={'skeleton-input-component'} /></Col>
                                            <Col sm={24} md={12}><Skeleton className={'skeleton-input-component'} /></Col>
                                            <Col sm={24} md={12}><Skeleton className={'skeleton-input-component'} /></Col>
                                        </Row>
                                        <div className="text-right mt-5">
                                            <div><Skeleton className={'skeleton-group-button'} /></div>
                                        </div>
                                    </div>
                                </div>
                                : <Row className={`${classes.contents}`} >
                                    {/* Information And Coupon */}
                                    <Col span={24}>
                                        {/* Subcription plan detail */}
                                        <div style={Style.rowInfo}>
                                            <Row>
                                                {/* image */}
                                                <Col span={!below768 ? 12 : 10} style={{ textAlign: !below768 ? 'left' : 'center' }}>
                                                    <div className={`${classes.contentImage}`} >
                                                        <img
                                                            src={APP_URL.UPLOAD_PATH + '/' + IMAGE_PATH.SUBSCRIPTION + subscriptionDetail.imageName}
                                                        />
                                                    </div>
                                                </Col>
                                                {
                                                    isMegreLayout
                                                    ? <>
                                                        {/* Information */}
                                                        <Col span={!below768 ? 12 : 14}>
                                                            <h5 style={{ lineHeight: '26.06px', fontSize: '18px', fontWeight: 700, color: '#595757' }}>{initValues.name}</h5>
                                                            <div>
                                                                <h5 style={{ fontSize: '13px', lineHeight: '18.82px', fontWeight: 400, color: '#595757' }}>
                                                                    <span>{`${t('label.price')}: `}</span>
                                                                    {
                                                                        (subscriptionDetail.discountPrice !== subscriptionDetail.price) &&
                                                                                        <del style={{ fontSize: '1rem', color: '#929292' }} className="mr-2">{values.priceRoot}</del>
                                                                    }
                                                                    {values.price}
                                                                    {` (${t('label.inclusiveTax', { value: '10%' })})`}
                                                                </h5>
                                                            </div>
                                                            <div className='mb-3'>
                                                                <span style={{ fontSize: '13px', lineHeight: '18.82px', fontWeight: 400, color: '#999999' }}>{t('label.duration')}: {values.duration}</span>
                                                            </div>
                                                            {
                                                                subscriptionDetail.numberFreeTerm ? <div className="mb-3" style={{ fontSize: '13px', lineHeight: '18.82px', fontWeight: 400, color: '#999999' }}>
                                                                <span>{t('label.numberFreePeriod')}: {returnNumberFreePeriod(subscriptionDetail.numberFreeTerm)}</span>
                                                                </div> : null
                                                            }
                                                            {
                                                                subscriptionDetail.subscriptionDiscountType &&
                                                                <div className={`${classes.notPadding} w-100`} style={{ display: 'flex', flexDirection: 'column', borderTop: `1px solid ${style.borderColor || '#fff'}` }}>
                                                                    <h5 className="justify-content-start my-2" style={{ display: 'flex', color: '#595757', fontSize: '13px', lineHeight: '18.82px', fontWeight: 400 }}>{t('label.discountDetail')}</h5>
                                                                    <p className="justify-content-start mb-2 px-2 text-break" style={{ display: 'flex', color: '#999999', fontSize: '13px', lineHeight: '18.82px', fontWeight: 400 }}>{t(subscriptionDetail.subscriptionDiscountType === 'ORDINAL' ? 'text.discountMessageOrdinal' : 'text.discountMessage', { name: subscriptionDetail.nameSubscription, discount: subscriptionDetail.discount })}</p>
                                                                </div>
                                                            }
                                                            <div className={`${classes.notPadding} card-body `}>
                                                                <ul className="list-group list-group-flush pb-1">
                                                                    <div style={{ color: '#595757', fontSize: '13px', lineHeight: '18.82px', fontWeight: 400 }}>{t('label.contentGroups')}</div>
                                                                    <div className="list-group-item" style={{ backgroundColor: styleBody.backgroundColor ? styleBody.backgroundColor : '', padding: 0, marginBottom: 10 }}>
                                                                        {
                                                                            subscriptionDetail.subscriptionContentGroups && subscriptionDetail.subscriptionContentGroups.map((contentGroup, index) => {
                                                                                if (index < subscriptionDetail.subscriptionContentGroups.length - 1) {
                                                                                    return (
                                                                                        <span key={contentGroup.contentGroupId} style={{ backgroundColor: styleBody.backgroundColor ? styleBody.backgroundColor : '', color: '#999999', fontSize: '13px', lineHeight: '18.82px', fontWeight: 400 }}>
                                                                                            {`${contentGroup.contentGroupName}/ `}
                                                                                        </span>
                                                                                    );
                                                                                } else {
                                                                                    return (
                                                                                        <span key={contentGroup.contentGroupId} style={{ backgroundColor: styleBody.backgroundColor ? styleBody.backgroundColor : '', color: '#999999', fontSize: '13px', lineHeight: '18.82px', fontWeight: 400 }}>
                                                                                        {contentGroup.contentGroupName}
                                                                                        </span>
                                                                                    );
                                                                                }
                                                                            })
                                                                        }
                                                                    </div>
                                                                </ul>
                                                            </div>
                                                            {
                                                                !below768 &&
                                                                <div style={{ fontSize: '13px', lineHeight: '18.82px', fontWeight: 400, color: '#595757' }}>
                                                                    <div>
                                                                        <span>{t('label.usagePeriod')}: {initValues.usagePeriod}</span>
                                                                    </div>
                                                                    <div>
                                                                        <span>{t('label.nextPaymentDate')}: {initValues.nextPaymentDate}</span>
                                                                    </div>
                                                                    <div>
                                                                        <span>{t('text.noteConfirmationOfYourOrder1')}</span>
                                                                    </div>
                                                                    {subscriptionDetail.description && <div style={{ margin: '10px 0px' }}>
                                                                    {
                                                                        subscriptionDetail.description && <div>
                                                                        {/* <div><hr/></div> */}
                                                                        <div style={{ width: '100%', wordBreak: 'break-word', color: '#595757', fontSize: '13px', lineHeight: '18.82px', fontWeight: 400 }}>{subscriptionDetail.description.includes('\n') ? subscriptionDetail.description.split('\n').map((t, key) => {
                                                                            return <p key={key} style={{ margin: '0px' }}>{t}</p>;
                                                                        }) : subscriptionDetail.description}</div>
                                                                        {/* <div><hr/></div> */}
                                                                        </div>
                                                                    }
                                                                    </div>}
                                                                    {/* Coupon */}
                                                                    <div style={{ marginBottom: '20px', marginTop: '20px' }}>
                                                                        <FormItem name="codeCoupon" label={t('label.codeCoupon')}>
                                                                            {({ value, onChange }) => (
                                                                                <InputFieldButtonRight
                                                                                    name="codeCoupon"
                                                                                    type="text"
                                                                                    value={value}
                                                                                    rightButtonLabel={t(`button.${isApplyCoupon ? 'cancel' : 'apply'}`)}
                                                                                    placeholder={t('label.codeCoupon')}
                                                                                    onChange={onChange}
                                                                                    disabledButton={!value || value.trim().length === 0 || isCouponUserDetailLoad}
                                                                                    maxLength={64}
                                                                                    disabled={isApplyCoupon || isCouponUserDetailLoad}
                                                                                    onRightButtonClick={() => {
                                                                                        if (isApplyCoupon) {
                                                                                            setIsApplyCoupon(false);
                                                                                            setInitValues({
                                                                                                ...initValues,
                                                                                                codeCoupon: '',
                                                                                                discountPrice: '¥0',
                                                                                                netPrice: '¥' + formatThousandsNumber(subscriptionDetail.discountPrice),
                                                                                                taxPrice: '¥' + formatThousandsNumber(tax10(subscriptionDetail.discountPrice)),
                                                                                                totalPayment: '¥' + formatThousandsNumber(addTax10(subscriptionDetail.discountPrice))
                                                                                            });
                                                                                            setCouponCode(null);
                                                                                            setCouponCodeTemp(null);
                                                                                            return;
                                                                                        }
                                                                                        setCouponCodeTemp(value.trim());
                                                                                        dispatch(fetchCouponUser({ couponCode: value.trim(), subscriptionPlanId: subscriptionDetail.id }));
                                                                                    }}
                                                                                />
                                                                            )}
                                                                        </FormItem>
                                                                    </div>
                                                                    <hr/>
                                                                    {/* info price */}
                                                                    <RenderInfoPrice
                                                                        isMegreLayout={isMegreLayout}
                                                                        isMobile={below768}
                                                                        values={values}
                                                                        isUpdateCard={isUpdateCard}
                                                                        handleUpdateCard={handleUpdateCard}
                                                                        cardData={cardData}
                                                                        setCardData={setCardData}
                                                                        setIsValidCard={setIsValidCard}
                                                                        setInitValue={setInitValues}
                                                                    />
                                                                    <div><hr/></div>
                                                                    <div style={Style.selectPaymentMethod}>
                                                                        <div className="text-right" style={Style.selectPaymentMethodFormGroup}>
                                                                            <AppButton
                                                                                style={{ width: '100%', backgroundColor: '#00B27B', borderColor: '#00B27B' }}
                                                                                className="btn btn-info"
                                                                                // variant="contained"
                                                                                // color="primary"
                                                                                // onClick={() => submit(values)}
                                                                                // onClick={() => router.push(`${servicePath ? '/'+servicePath : ''}/thank-you`)}
                                                                                type='submit'
                                                                                disabled={isCouponUserDetailLoad || isVerify || isLoading}
                                                                            >
                                                                                {t(isGakkenPayment ? 'button.selectPaymentMethod' : 'button.register')}
                                                                            </AppButton>
                                                                            <AppButton
                                                                                style={{ margin: '0', width: '100%', marginTop: 10, backgroundColor: 'white', borderColor: '#d0d0d0', color: '#585757' }}
                                                                                className="btn btn-warning"
                                                                                color="warning"
                                                                                // variant="contained"
                                                                                onClick={onCancel}
                                                                            >
                                                                                {t('button.cancelOrder')}
                                                                            </AppButton>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            }
                                                        </Col>
                                                        {
                                                            below768 &&
                                                            <Col span={24} style={{ paddingLeft: 5, paddingRight: 5, fontSize: '13px', lineHeight: '18.82px', fontWeight: 400, color: '#595757' }}>
                                                                <div>
                                                                    <span>{t('label.usagePeriod')}: {initValues.usagePeriod}</span>
                                                                </div>
                                                                <div>
                                                                    <span>{t('label.nextPaymentDate')}: {initValues.nextPaymentDate}</span>
                                                                </div>
                                                                <div>
                                                                    <span>{t('text.noteConfirmationOfYourOrder1')}</span>
                                                                </div>
                                                                {below768 && subscriptionDetail.description && <div style={{ margin: '10px 0px' }}>
                                                                    {
                                                                    subscriptionDetail.description && <div>
                                                                        {/* <div><hr/></div> */}
                                                                        <div style={{ width: '100%', wordBreak: 'break-word' }}>{subscriptionDetail.description.includes('\n') ? subscriptionDetail.description.split('\n').map((t, key) => {
                                                                        return <p key={key} style={{ margin: '0px' }}>{t}</p>;
                                                                        }) : subscriptionDetail.description}</div>
                                                                        {/* <div><hr/></div> */}
                                                                    </div>
                                                                    }
                                                                </div>}
                                                                {/* Coupon */}
                                                                <div style={{ marginBottom: '20px' }}>
                                                                    <FormItem name="codeCoupon" label={t('label.codeCoupon')}>
                                                                        {({ value, onChange }) => (
                                                                            <InputFieldButtonRight
                                                                                name="codeCoupon"
                                                                                type="text"
                                                                                value={value}
                                                                                rightButtonLabel={t(`button.${isApplyCoupon ? 'cancel' : 'apply'}`)}
                                                                                placeholder={t('label.codeCoupon')}
                                                                                onChange={onChange}
                                                                                disabledButton={!value || value.trim().length === 0 || isCouponUserDetailLoad}
                                                                                maxLength={64}
                                                                                disabled={isApplyCoupon || isCouponUserDetailLoad}
                                                                                
                                                                                onRightButtonClick={() => {
                                                                                    if (isApplyCoupon) {
                                                                                    setIsApplyCoupon(false);
                                                                                    setInitValues({
                                                                                        ...initValues,
                                                                                        codeCoupon: '',
                                                                                        discountPrice: '¥0',
                                                                                        netPrice: '¥' + formatThousandsNumber(subscriptionDetail.discountPrice),
                                                                                        taxPrice: '¥' + formatThousandsNumber(tax10(subscriptionDetail.discountPrice)),
                                                                                        totalPayment: '¥' + formatThousandsNumber(addTax10(subscriptionDetail.discountPrice))
                                                                                    });
                                                                                    setCouponCode(null);
                                                                                    setCouponCodeTemp(null);
                                                                                    return;
                                                                                    }
                                                                                    setCouponCodeTemp(value.trim());
                                                                                    dispatch(fetchCouponUser({ couponCode: value.trim(), subscriptionPlanId: subscriptionDetail.id }));
                                                                                }}
                                                                            />
                                                                        )}
                                                                    </FormItem>
                                                                </div>
                                                                <hr/>
                                                                {/* info price */}
                                                                <RenderInfoPrice
                                                                    isMegreLayout={isMegreLayout}
                                                                    isMobile={below768}
                                                                    values={values}
                                                                    isUpdateCard={isUpdateCard}
                                                                    handleUpdateCard={handleUpdateCard}
                                                                    cardData={cardData}
                                                                    setCardData={setCardData}
                                                                    setIsValidCard={setIsValidCard}
                                                                    setInitValue={setInitValues}
                                                                />
                                                                <div><hr/></div>
                                                                <div style={Style.selectPaymentMethod}>
                                                                    <div className="text-right" style={Style.selectPaymentMethodFormGroup}>
                                                                        <AppButton
                                                                            style={{ width: '100%', backgroundColor: '#00B27B', borderColor: '#00B27B' }}
                                                                            className="btn btn-info"
                                                                            // variant="contained"
                                                                            color="info"
                                                                            type='submit'
                                                                            // onClick={() => submit(values)}
                                                                            // onClick={() => router.push(`${servicePath ? '/'+servicePath : ''}/thank-you`)}
                                                                            disabled={isCouponUserDetailLoad || isVerify || isLoading}
                                                                        >
                                                                            {t(isGakkenPayment ? 'button.selectPaymentMethod' : 'button.register')}
                                                                        </AppButton>
                                                                        <AppButton
                                                                            style={{ margin: '0', width: '100%', marginTop: 10, backgroundColor: '#E44A4A', borderColor: '#d0d0d0', color: '#ffffff' }}
                                                                            className="btn btn-warning"
                                                                            // variant="contained"
                                                                            color="warning"
                                                                            // type="button"
                                                                            onClick={onCancel}
                                                                        >
                                                                            {t('button.cancelOrder')}
                                                                        </AppButton>
                                                                    </div>
                                                                </div>
                                                            </Col>
                                                        }
                                                    </>
                                                    : <>
                                                        {/* Information */}
                                                        <Col span={!below768 ? 12 : 14} >
                                                            <h5>{initValues.name}</h5>
                                                            <div>
                                                                <h5 className="text-bold">
                                                                <span>{`${t('label.price')}: `}</span>
                                                                {
                                                                    (subscriptionDetail.discountPrice !== subscriptionDetail.price) &&
                                                                <del style={{ fontSize: '1rem', color: '#929292' }} className="mr-2">{values.priceRoot}</del>
                                                                }
                                                                {values.price}
                                                                {` (${t('label.inclusiveTax', { value: '10%' })})`}
                                                                </h5>
                                                            </div>
                                                            <div className='mb-3'>
                                                                <span>{t('label.duration')}: {values.duration}</span>
                                                            </div>
                                                            {
                                                                subscriptionDetail.numberFreeTerm
                                                                ? <div className="mb-3">
                                                                    <span>{t('label.numberFreePeriod')}: {returnNumberFreePeriod(subscriptionDetail.numberFreeTerm)}</span>
                                                                </div>
                                                                : null
                                                            }
                                                            {
                                                                subscriptionDetail.subscriptionDiscountType &&
                                                                <div className={`${classes.notPadding}  w-100`} style={{ display: 'flex', flexDirection: 'column', borderTop: `1px solid ${style.borderColor || '#fff'}` }}>
                                                                    <h5 className="justify-content-start my-2" style={{ display: 'flex' }}>{t('label.discountDetail')}</h5>
                                                                    <p className="justify-content-start mb-2 px-2 text-break" style={{ display: 'flex' }}>{t(subscriptionDetail.subscriptionDiscountType === 'ORDINAL' ? 'text.discountMessageOrdinal' : 'text.discountMessage', { name: subscriptionDetail.nameSubscription, discount: subscriptionDetail.discount })}</p>
                                                                </div>
                                                            }
                                                            <div className={`${classes.notPadding} card-body `} style={{ borderTop: `1px solid ${style.borderColor || '#fff'}` }}>
                                                                <ul className="list-group list-group-flush pb-1">
                                                                <div>{t('label.contentGroups')}</div>
                                                                <div className="list-group-item" style={{ backgroundColor: styleBody.backgroundColor ? styleBody.backgroundColor : '' }}>
                                                                    {
                                                                        subscriptionDetail.subscriptionContentGroups && subscriptionDetail.subscriptionContentGroups.map(contentGroup => {
                                                                            return (
                                                                                <div className="flex items-center" key={contentGroup.contentGroupId} style={{ backgroundColor: styleBody.backgroundColor ? styleBody.backgroundColor : '' }}>
                                                                                    <CircleCheck className="text-success mr-1" size={18}/>
                                                                                    {contentGroup.contentGroupName}
                                                                                </div>
                                                                            );
                                                                        })
                                                                    }
                                                                </div>
                                                                </ul>
                                                            </div>
                                                            {
                                                                !below768 &&
                                                                <>
                                                                    <div>
                                                                        <span>{t('label.usagePeriod')}: {initValues.usagePeriod}</span>
                                                                    </div>
                                                                    <div>
                                                                        <span>{t('label.nextPaymentDate')}: {initValues.nextPaymentDate}</span>
                                                                    </div>
                                                                    <div>
                                                                        <span>{t('text.noteConfirmationOfYourOrder1')}</span>
                                                                    </div>
                                                                    {below768 && subscriptionDetail.description && <div style={{ marginTop: '8px' }}>
                                                                    {
                                                                        subscriptionDetail.description &&
                                                                        <div>
                                                                            <div><hr/></div>
                                                                            <div style={{ width: '100%', wordBreak: 'break-word' }}>{subscriptionDetail.description.includes('\n') ? subscriptionDetail.description.split('\n').map((t, key) => {
                                                                                return <p key={key} style={{ margin: '0px' }}>{t}</p>;
                                                                            }) : subscriptionDetail.description}</div>
                                                                            <div><hr/></div>
                                                                        </div>
                                                                    }
                                                                    </div>}
                                                                    {/* Coupon */}
                                                                    <div style={{ marginBottom: '20px' }}>
                                                                        
                                                                        <FormItem name="codeCoupon" label={t('label.codeCoupon')}>
                                                                            {({ value, onChange }) => (
                                                                                <InputFieldButtonRight
                                                                                    type="text"
                                                                                    value={value}
                                                                                    rightButtonLabel={t(`button.${isApplyCoupon ? 'cancel' : 'apply'}`)}
                                                                                    placeholder={t('label.codeCoupon')}
                                                                                    onChange={onChange}
                                                                                    disabledButton={!value || value.trim().length === 0 || isCouponUserDetailLoad}
                                                                                    maxLength={64}
                                                                                    disabled={isApplyCoupon || isCouponUserDetailLoad}
                                                                                    onRightButtonClick={() => {
                                                                                        if (isApplyCoupon) {
                                                                                            setIsApplyCoupon(false);
                                                                                            setInitValues({
                                                                                                ...initValues,
                                                                                                codeCoupon: '',
                                                                                                discountPrice: '¥0',
                                                                                                netPrice: '¥' + formatThousandsNumber(subscriptionDetail.discountPrice),
                                                                                                taxPrice: '¥' + formatThousandsNumber(tax10(subscriptionDetail.discountPrice)),
                                                                                                totalPayment: '¥' + formatThousandsNumber(addTax10(subscriptionDetail.discountPrice))
                                                                                            });
                                                                                            setCouponCode(null);
                                                                                            setCouponCodeTemp(null);
                                                                                            return;
                                                                                        }
                                                                                        setCouponCodeTemp(value.trim());
                                                                                        dispatch(fetchCouponUser({ couponCode: value.trim(), subscriptionPlanId: subscriptionDetail.id }));
                                                                                    }}
                                                                                />
                                                                            )}
                                                                        </FormItem>
                                                                    </div>
                                                                    <hr/>
                                                                    {/* info price */}
                                                                    <RenderInfoPrice
                                                                        isMegreLayout={isMegreLayout}
                                                                        isMobile={below768}
                                                                        values={values}
                                                                        isUpdateCard={isUpdateCard}
                                                                        handleUpdateCard={handleUpdateCard}
                                                                        cardData={cardData}
                                                                        setCardData={setCardData}
                                                                        setIsValidCard={setIsValidCard}
                                                                        setInitValue={setInitValues}
                                                                    />
                                                                    <div><hr/></div>
                                                                    <div style={Style.selectPaymentMethod}>
                                                                        <div className="text-right" style={Style.selectPaymentMethodFormGroup}>
                                                                            <AppButton
                                                                                style={{ width: '100%', backgroundColor: '#00B27B', borderColor: '#00B27B' }}
                                                                                className="btn btn-info"
                                                                                // variant="contained"
                                                                                color="info"
                                                                                type='submit'
                                                                                // onClick={() => submit(values)}
                                                                                disabled={isCouponUserDetailLoad || isVerify || isLoading}
                                                                            >
                                                                                {t(isGakkenPayment ? 'button.selectPaymentMethod' : 'button.register')}
                                                                            </AppButton>
                                                                            <AppButton
                                                                                style={{ margin: '0', width: '100%', marginTop: 10, backgroundColor: 'white', borderColor: '#d0d0d0', color: '#000' }}
                                                                                className="btn btn-warning"
                                                                                color="warning"
                                                                                // variant="contained"
                                                                                // type="button"
                                                                                onClick={onCancel}
                                                                            >
                                                                                {t('button.cancelOrder')}
                                                                            </AppButton>
                                                                        </div>
                                                                    </div>
                                                                </>
                                                            }
                                                            
                                                        </Col>
                                                        {
                                                            below768 &&
                                                            <Col span={24}  style={{ paddingLeft: 5, paddingRight: 5 }}>
                                                                <div>
                                                                    <span>{t('label.usagePeriod')}: {initValues.usagePeriod}</span>
                                                                </div>
                                                                <div>
                                                                    <span>{t('label.nextPaymentDate')}: {initValues.nextPaymentDate}</span>
                                                                </div>
                                                                <div>
                                                                    <span>{t('text.noteConfirmationOfYourOrder1')}</span>
                                                                </div>
                                                                {below768 && subscriptionDetail.description && <div style={{ marginTop: '8px' }}>
                                                                    {
                                                                    subscriptionDetail.description && <div>
                                                                        <div><hr/></div>
                                                                        <div style={{ width: '100%', wordBreak: 'break-word' }}>{subscriptionDetail.description.includes('\n') ? subscriptionDetail.description.split('\n').map((t, key) => {
                                                                        return <p key={key} style={{ margin: '0px' }}>{t}</p>;
                                                                        }) : subscriptionDetail.description}</div>
                                                                        <div><hr/></div>
                                                                    </div>
                                                                    }
                                                                </div>}
                                                                {/* Coupon */}
                                                                <div style={{ marginBottom: '20px' }}>
                                                                    <FormItem name="codeCoupon" label={t('label.codeCoupon')}>
                                                                        {({ value, onChange }) => (
                                                                            <InputFieldButtonRight
                                                                                value={value}
                                                                                rightButtonLabel={t('label.codeCoupon')}
                                                                                placeholder={t('label.codeCoupon')}
                                                                                onChange={onChange}
                                                                                disabled={isApplyCoupon || isCouponUserDetailLoad}
                                                                                disabledButton={!value || value.trim().length === 0 || isCouponUserDetailLoad}
                                                                                maxLength={64}
                                                                                onRightButtonClick={() => {
                                                                                    if (isApplyCoupon) {
                                                                                        setIsApplyCoupon(false);
                                                                                        setInitValues({
                                                                                            ...initValues,
                                                                                            codeCoupon: '',
                                                                                            discountPrice: '¥0',
                                                                                            netPrice: '¥' + formatThousandsNumber(subscriptionDetail.discountPrice),
                                                                                            taxPrice: '¥' + formatThousandsNumber(tax10(subscriptionDetail.discountPrice)),
                                                                                            totalPayment: '¥' + formatThousandsNumber(addTax10(subscriptionDetail.discountPrice))
                                                                                        });
                                                                                        setCouponCode(null);
                                                                                        setCouponCodeTemp(null);
                                                                                        return;
                                                                                    }
                                                                                    setCouponCodeTemp(value.trim());
                                                                                    dispatch(fetchCouponUser({ couponCode: value.trim(), subscriptionPlanId: subscriptionDetail.id }));
                                                                                }}
                                                                            />
                                                                        )}
                                                                    </FormItem>
                                                                </div>
                                                                <hr/>
                                                                {/* info price */}
                                                                <RenderInfoPrice
                                                                    isMegreLayout={isMegreLayout}
                                                                    isMobile={below768}
                                                                    values={values}
                                                                    setInitValue={setInitValues}
                                                                    isUpdateCard={isUpdateCard}
                                                                    handleUpdateCard={handleUpdateCard}
                                                                    cardData={cardData}
                                                                    setCardData={setCardData}
                                                                    setIsValidCard={setIsValidCard}
                                                                />
                                                                <div><hr/></div>
                                                                <div style={Style.selectPaymentMethod}>
                                                                    <div className="text-right" style={Style.selectPaymentMethodFormGroup}>
                                                                        <AppButton
                                                                            style={{ width: '100%', backgroundColor: '#00B27B', borderColor: '#00B27B' }}
                                                                            className="btn btn-info"
                                                                            // variant="contained"
                                                                            type='submit'
                                                                            // onClick={() => submit(values)}
                                                                            // onClick={() => router.push(`${servicePath ? '/'+servicePath : ''}/thank-you`)}
                                                                            disabled={isCouponUserDetailLoad || isVerify || isLoading}
                                                                        >
                                                                            {t(isGakkenPayment ? 'button.selectPaymentMethod' : 'button.register')}
                                                                        </AppButton>
                                                                        <AppButton
                                                                            style={{ margin: '0', width: '100%', marginTop: 10, backgroundColor: '#E44A4A', borderColor: '#d0d0d0', color: '#ffffff' }}
                                                                            className="btn btn-warning"
                                                                            // variant="contained"
                                                                            color="warning"
                                                                            // type="button"
                                                                            onClick={onCancel}
                                                                        >
                                                                            {t('button.cancelOrder')}
                                                                        </AppButton>
                                                                    </div>
                                                                </div>
                                                            </Col>
                                                        }
                                                    </>
                                                }
                                            </Row>
                                        </div>
                                    </Col>
                                </Row>
                            }
                        </div>
                    }
                </FormWrapper>
            }
            
           
        </Fragment>
    );
  };



    type PropsRenderInfoPrice = {
        values: any;
        isUpdateCard: boolean;
        handleUpdateCard: any;
        isMegreLayout: boolean;
        isMobile: boolean;
        cardData: CardDataUpdateType;
        setCardData: any;
        setIsValidCard: any;
        setInitValue: any;
    };
    type RefType = {
        markTouched: () => void;
    };
    const RenderInfoPrice = (props: PropsRenderInfoPrice) => {
        const { values, isUpdateCard, handleUpdateCard, isMegreLayout, isMobile, cardData, setCardData, setIsValidCard, setInitValue } = props;
        const t = useTranslations("");

        const authUser = useAppSelector(getAuthInfo) || {} as any;
        const viewSettings = useAppSelector(getViewSettings);

        const case1 = isMegreLayout && !isMobile;
        
        
        const Style: any = {
            row1: {
                marginTop: '10px',
                color: '#585757'
            },
            row: {
                marginTop: '10px'
            },
            discountPrice1: {
                color: '#E44A4A',
            },
            discountPrice: {
                color: 'red'
            },
            toalPaymentAmount1: {
                color: '#585757',
                lineHeight: '26.06px',
                fontSize: '18px',
                fontWeight: 700
            },
            toalPaymentAmount: {
                fontWeight: 'bold'
            },
            totalPayment1: {
                textAlign: 'right',
                color: '#585757',
                lineHeight: '26.06px',
                fontSize: '18px',
                fontWeight: 700
            },
            totalPayment: {
                textAlign: 'right',
                fontWeight: 'bold'
            }
        };        

        const paymentMethodMdSize = isMobile ? 24 : 16;
        return (
            <Row  style={case1 ? Style.row1 : Style.row}>
                <Col span={16} className="mb-2">
                    <span >{t('label.priceWithoutTax')}: </span>
                </Col>
                <Col span={8} className="mb-2" style={{ textAlign: 'right' }}>
                    <span>{values.priceWithoutTax}</span>
                </Col>
                <Col span={16} className="mb-2">
                    <span style={case1 ? Style.discountPrice1 : Style.discountPrice}>{t('label.couponDiscount')}:</span>
                </Col>
                <Col span={8} className="mb-2" style={{ textAlign: 'right' }}>
                    <span style={case1 ? Style.discountPrice1 : Style.discountPrice}>{`- ${values.discountPrice}`}</span>
                </Col>
                <Col span={16} className="mb-2">
                    <span >{t('label.netPrice')}: </span>
                </Col>
                <Col span={8} className="mb-2" style={{ textAlign: 'right' }}>
                    <span>{values.netPrice}</span>
                </Col>
                <Col span={16} className="mb-2">
                    <span>{`${t('label.tax', { value: '10%' })}: `}</span>
                </Col>
                <Col span={8} className="mb-2" style={{ textAlign: 'right' }}>
                    <span>{values.taxPrice}</span>
                </Col>
                <Col span={16} className="mb-2">
                    <span style={case1 ? Style.toalPaymentAmount1 : Style.toalPaymentAmount}>{`${t('label.toalPaymentAmount')}: `}</span>
                </Col>
                <Col span={8} className="mb-2" style={case1 ? Style.totalPayment1 : Style.totalPayment}>
                    <span>{values.totalPayment}</span>
                </Col>
                {
                    viewSettings.paymentGateway !== PaymentMethod.GAKKEN_ID &&
                    <Fragment>
                        <Col span={24} className="mb-2">
                            {t('label.paymentMethod')}
                        </Col>
                        <Col span={24} className={'mb-2'}>
                            {/* CreditCardInput */} 
                            {
                                (!authUser.cardNumber || isUpdateCard) &&
                                <InputUpdateCard setCardData={setCardData} cardData={cardData} setIsValidCard={setIsValidCard}/>
                            }
                            {
                                authUser.cardNumber &&
                                <Fragment>
                                    {
                                        !isUpdateCard &&
                                        <div style={{ display: 'flex', width: '100%' }}>
                                            <CreditCard
                                                className="mr-1"
                                                style={{
                                                    display: 'flex',
                                                    alignItems: 'center'
                                                }}
                                            />
                                            {authUser.cardNumber}
                                        </div>
                                    }
                                </Fragment>
                            }
                        </Col>
                        <Col sm={24} md={isMobile ? 6 :  24} className="mb-2">
                            {
                                authUser.cardNumber &&
                                <AppButton
                                    // variant="contained"
                                    // type="primary"
                                    color={isUpdateCard ? "warning" : "info"}
                                    type="button"
                                    onClick={() => {
                                        handleUpdateCard();
                                    }}
                                >
                                    {t(isUpdateCard ? 'button.cancel' : 'button.update')}
                                </AppButton>
                            }
                        </Col>
                        {
                            viewSettings.paymentGateway === PaymentMethod.VERITRANS &&
                            <Col sm={24} md={isMobile ? 24 : 16} className='mb-2'>
                                <FormItem name="cardHolderEmail" label={t('label.cardHolderEmail')}>
                                    {({ value, ref, ...field }) => (
                                        <AppInput
                                            ref={ref}
                                            onChange={(e) => {
                                                setInitValue({ ...values, cardHolderEmail: e.target.value });
                                            }}
                                            inputType="default"
                                            value={value}
                                            // {...field}
                                        />
                                    )}
                                </FormItem>
                                <FormItem name="cardHolderName" label={t('label.cardHolderName')}>
                                    {({ value, ref, ...field }) => (
                                        <AppInput
                                            ref={ref}
                                            inputType="default"
                                            onChange={(e) => {
                                                setInitValue({ ...values, cardHolderName: e.target.value });
                                            }}
                                            value={value}
                                            // {...field}
                                        />
                                    )}
                                </FormItem>
                            </Col>
                        }
                    </Fragment>
                }
            </Row>
        );
    }
    