"use client"
import { APP_URL, DURATION_MAP, IMAGE_PATH, LAYOUT_SETTING, 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 { STORAGE_KEYS } from "@/types/common";
import { ServiceViewSettings } from "@/types/serviceAdmin";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { Fragment, useEffect, useState } from "react";
import { Col, Row, Skeleton } from "antd";
import { FormItem, FormWrapper } from "../ui/form";
import { CreditCard } from "lucide-react";
import AppInput from "../ui/input/input";
import { confirmOrderReceive, fetchGakkenPaymentInfo, getIsPaymentError, getIsPaymentSuccess,resetCreateOrderReceive, resetCreateOrderReceiveVeritrans, resetGakkenPaymentInfo, resetPaymentError, veritransConfirmOrder } from "@/lib/redux/features/payment";
import { getAuthInfo } from "@/lib/redux/features/auth";
import { showToast } from "../toast/showToast";
import OrderConfirmation from "./order-confirmation";
import { z } from "zod";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Step, StepLabel, Stepper } from "@mui/material";
import { makeStyles } from "tss-react/mui";
import useResponsive from "@/hooks/useResponsive";
import { addTax10, formatThousandsNumber, tax10 } from "@/lib/utils";
import moment from "moment";
import { fetchSubscriptionDetail, getIsSubscriptionDetailLoad, getSubscriptionDetail } from "@/lib/redux/features/subscription";
import { fetchCouponUser, getCouponUserDetail, getCouponUserDetailLoad } from "@/lib/redux/features/coupon";
import AppButton from "../ui/button/app-button";

// type PropsType = { viewSettings?: ServiceViewSettings };
type MakeStylesType = {
    below768: boolean;
    isMegreLayout: boolean;
}

const useStyle = makeStyles<MakeStylesType>()((theme, { below768, isMegreLayout }) => ({
    contentImage: {
      padding: isMegreLayout ? '0 5px' : '',
      marginBottom: '0.5rem',
      marginRight: '0.5rem',
      position: 'relative',
      overflow: below768 ? 'initial' : 'hidden',
      height: '100%',
      // border: '1px solid #d0d0d0',
      '& img': {
        maxHeight: below768 ? 180 : 300,
        maxWidth: 300,
        objectFit: 'contain',
        minWidth: below768 ? (isMegreLayout ? 120 : 150) : 180
      },
      display: !below768 ? 'flex' : 'flex',
      width: !below768 ? '100%' : '100%',
      justifyContent: 'center',
      alignItems: 'flex-start'
    },
    imageSubscription: {
      objectFit: 'contain',
      height: '100%',
      width: '100%'
    },
    progressBar: {
      '& .MuiStep-horizontal': !isMegreLayout ? {} : {
        paddingLeft: 0,
        paddingRight: 0
      }
    }
}));



export default function VeritransPaymentConfirm (props: any) {
   
    const t = useTranslations("");
    const dispatch = useAppDispatch();
    const router = useRouter();
    const { below768 } = useResponsive();

    const servicePath = useAppSelector(getServicePath);
    const currentDomain = useAppSelector(getCompanyDomain);
    const viewSettings = useAppSelector(getViewSettings);
    const cacheSubscriptionId = StorageHelper.getSessionItem(STORAGE_KEYS.subsId);
    const isPaymentSuccess = useAppSelector(getIsPaymentSuccess);
    const isPaymentError = useAppSelector(getIsPaymentError);
    const layoutViewPage = useAppSelector(getLayoutViewPage);
    const subscriptionDetail = useAppSelector(getSubscriptionDetail);
    const isSubscriptionDetailLoad = useAppSelector(getIsSubscriptionDetailLoad);
    const isCouponUserDetailLoad = useAppSelector(getCouponUserDetailLoad);
    const styleBody = useAppSelector(getBodySetting);
    const style = useAppSelector(getContentDetailSetting);

    const couponUserDetail = useAppSelector(getCouponUserDetail);
    

    const [isLoading, setIsLoading] = useState(false);
    const [initValues, setInitValues] = useState<any>({
        name: '',
        contentGroups: '',
        discount: '',
        duration: '',
        price: '',
        codeCoupon: '',
        discountPrice: '¥0',
        priceRoot: '',
        usagePeriod: '',
        nextPaymentDate: '',
        numberFreeTerm: '',
        costForOneYear: ''
    });
  
    const couponCode = StorageHelper.getSessionItem(STORAGE_KEYS.couponCode);
    const search = window.location.search;
    const userStore = !servicePath || servicePath === '' ? currentDomain : servicePath;
    const isAuthen = StorageHelper.getLocalObject(userStore);
    const isToken = StorageHelper.getCookie(userStore);
    const day = 1000 * 60 * 60 * 24;
    const isMegreLayout = layoutViewPage === LAYOUT_SETTING.HOME_LAYOUT_AND_SEARCH_LAYOUT.id;
  
    const { classes } = useStyle({ below768, isMegreLayout });
    const Style = {
        spin: {
          height: !below768 ? '100%' : '90%',
          width: '100%',
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
          zIndex: '1000',
          position: !below768 ? 'relative' : 'absolute'
        },
        discountPrice: {
          color: 'red'
        },
        rowInfo: {
          margin: '12px 0'
        },
        containerCenter: {
          width: '100%',
          display: 'flex',
          justifyContent: 'space-between'
        }
    };

    
    const submit = data => {
        if (viewSettings.paymentGateway === PaymentMethod.VERITRANS) {
          const orderId = search.includes('?couponCode=') ? search.split('&')[2].replace('OrderId=', '') : search.split('&')[1].replace('OrderId=', '');
          const couponCode = search.includes('?couponCode=') ? search.split('&')[0].replace('?couponCode=', '') : null;
          const request = {
            orderId: orderId,
            couponCode: couponCode,
            isClose: data.totalPayment === '¥0'
          };
          setIsLoading(true);
          dispatch(veritransConfirmOrder(request));
        }
    };
    const onCancel = async () => {
        router.push(`${servicePath ? '/'+servicePath : ''}/`);
        dispatch(resetCreateOrderReceiveVeritrans());
        showToast('error', t('toast.success.cancelVeritransPayment'));
        
    };
    
    const steps = [t('label.orderEntry'), t('label.confirmOrder'), t('label.orderComplete')];
    
    const returnNumberFreePeriod = _days => {
        return `${t('number.day', { days: _days })}`;
    };


    





    const formSchema = z
    .object({
        name: z.any(),
        contentGroups: z.any(),
        discount: z.any(),
        duration: z.any(),
        price: z.any(),
        codeCoupon: z.any(),
        discountPrice: z.any(),
        numberFreeTerm: z.any(),
        usagePeriod: z.any(),
        nextPaymentDate: z.any(),
        priceRoot: z.any(),
        netPrice: z.any(),
        taxPrice: z.any(),
        totalPayment: z.any(),
        createdDate: z.any(),
        expiredDate: z.any(),
        cardHolderEmail: z.any(),
        cardHolderName: z.any(),
        priceWithoutTax: z.any(),
    });
    
    type OrderConfirmationFormSchema = z.infer<typeof formSchema>;
    

    const orderConfirmationForm = useForm<OrderConfirmationFormSchema>({
        resolver: zodResolver(formSchema),
        defaultValues: { ...initValues }
    });

    const values = orderConfirmationForm.getValues();
    
    useEffect(() => {
        if (!cacheSubscriptionId) {
            router.push(`${servicePath ? '/'+servicePath : ''}/`);
        }
    }, []);
    
    useEffect(() => {
        if (!isToken && !isAuthen) {
            router.push(`${servicePath ? '/'+servicePath : ''}/`);
        }
    }, [isAuthen, isToken]);

    useEffect(() => {
        if (cacheSubscriptionId && couponCode) {
            dispatch(fetchCouponUser({ couponCode: couponCode, subscriptionPlanId: cacheSubscriptionId }));
        }
    }, [cacheSubscriptionId, couponCode]);

    useEffect(() => {
        if (isPaymentSuccess) {
            setIsLoading(false);
            router.push(`${servicePath ? '/'+servicePath : ''}/thank-you`);
        }
    }, [isPaymentSuccess, isPaymentError]);

    useEffect(() => {
        if (subscriptionDetail && subscriptionDetail.subscriptionContentGroups) {
            const { subscriptionContentGroups } = subscriptionDetail;
            let discountPrice = 0;
            if (couponUserDetail) {
                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 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,
                contentGroups: subscriptionContentGroups.map(x => x.contentGroupName).join(', '),
                duration: subscriptionDetail.duration + ' ' + t(`subscription.${DURATION_MAP.get(0)}`),
                price: '¥' + formatThousandsNumber(subscriptionDetail.discountPrice),
                priceRoot: '¥' + formatThousandsNumber(subscriptionDetail.price),
                netPrice: '¥' + formatThousandsNumber(netPrice),
                taxPrice: '¥' + formatThousandsNumber(tax10(netPrice)),
                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(),
                codeCoupon: couponCode,
                totalPayment: '¥' + formatThousandsNumber(addTax10(netPrice)),
                discountPrice: '¥' + formatThousandsNumber(discountPrice),
                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
            });
            StorageHelper.removeSessionItem(STORAGE_KEYS.subsId);
        }
    }, [subscriptionDetail, couponUserDetail]);


    useEffect(() => {
        if (cacheSubscriptionId) {
            dispatch(fetchSubscriptionDetail(cacheSubscriptionId));
        }
    }, [cacheSubscriptionId]);

    useEffect(() => {
        if (isPaymentError) {
            setIsLoading(false);
            dispatch(resetPaymentError());
        }
    }, [isPaymentError]);
    
    useEffect(() => {
        if (initValues && initValues.name) {
            orderConfirmationForm.reset(initValues);
        }
    }, [initValues]);
    
    
    if (isSubscriptionDetailLoad || isLoading) {
        return (
            <div className="flex items-center justify-center w-full">
                <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>
        );
    }

    return (
        <div style={{
            width: '100%',
            display: 'flex',
            flexWrap: 'wrap',
            flexDirection: 'column',
            alignContent: 'center'
          // justifyContent: 'center'
        }}>
            <Fragment>
                <FormWrapper<OrderConfirmationFormSchema>
                    form={orderConfirmationForm}
                    onSubmit={(data) => {
                        submit(data);
                    }}
                    layout="vertical"
                    className="space-y-4"
                >
                    
                    <div style={{ padding: isMegreLayout ? '0 20.8px' : '' }}>
                        <Row className={`${classes.progressBar}`}>
                            <Col span={24} style={{ padding: isMegreLayout ? '20px 0 0 0' : (!below768 ? '20px 0 0 50px' : '20px 0 0 20px') }}>
                                <h4 style={{ marginLeft: isMegreLayout ? 0 : 25, fontWeight: 700 }}>{t('title.confirmYourOrder')}</h4>
                            </Col>
                            <Col span={24} style={Style.containerCenter} >
                                <div style={{ width: '100%' }}>
                                    <Stepper activeStep={1} style={{ backgroundColor: styleBody.backgroundColor ? styleBody.backgroundColor : '', padding: !below768 ? (isMegreLayout ? '24px 0' : '24px') : '' }} alternativeLabel={!!below768}>
                                        {steps.map((text, index) => {
                                        return (
                                            <Step key={index}>
                                                <StepLabel>{text}</StepLabel>
                                            </Step>
                                        );
                                        })}
                                    </Stepper>
                                </div>
                            </Col>
                        </Row>
                        {/* content */}
                        <Row style={{ ...Style.rowInfo, padding: '0 15px' }}>
                            {/* image */}
                            <Col span={!below768 ? 12 : 10}>
                                <div className={`${classes.contentImage}`} >
                                <img
                                    src={APP_URL.UPLOAD_PATH + '/' + IMAGE_PATH.SUBSCRIPTION + subscriptionDetail.imageName}
                                />
                                </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="p-0 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="card-body p-0" 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 key={contentGroup.contentGroupId} style={{ backgroundColor: styleBody.backgroundColor ? styleBody.backgroundColor : '' }}>
                                                        <i className="far fa-check-circle text-success mr-1"></i>
                                                        {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>
                                        {/* info price */}
                                        <div style={Style.containerCenter}>
                                            <div>
                                                <Row>
                                                    <Col span={24}><hr style={{ borderTop: '1px solid ' }}/></Col>
                                                    <Col span={16} className="mb-2">
                                                        <span >{t('label.monthlyCost')}: </span>
                                                    </Col>
                                                    <Col span={8} className="mb-2" style={{ textAlign: 'right' }}>
                                                        <span>{values.price}</span>
                                                    </Col>
                                                    <Col span={16} className="mb-2">
                                                        <span style={Style.discountPrice}>{t('label.discountAmount')}:</span>
                                                    </Col>
                                                    <Col span={8} className="mb-2" style={{ textAlign: 'right' }}>
                                                        <span style={Style.discountPrice}>{`- ${values.discountPrice}`}</span>
                                                    </Col>
                                                    <Col span={16} className="mb-2">
                                                        <span >{t('label.totalAmount')}: </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.consumptionTax', { 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={{ fontWeight: 'bold' }}>{`${t('label.toalPaymentAmount')}: `}</span>
                                                    </Col>
                                                    <Col span={8} className="mb-2" style={{ textAlign: 'right', fontWeight: 'bold' }}>
                                                        <span>{values.totalPayment}</span>
                                                    </Col>
                                                    <Col span={24}><hr style={{ borderTop: '1px solid ' }} /></Col>
                                                </Row>
                                                <div className="text-right mt-4" style={{ ...Style.containerCenter, flexDirection: 'column' }}>
                                                    <AppButton
                                                        style={{ width: '100%', backgroundColor: '#00B27B', borderColor: '#00B27B' }}
                                                        className="btn btn-info mr-1"
                                                        // variant="contained"
                                                        // color="primary"
                                                        disabled={isCouponUserDetailLoad}
                                                        type="submit"
                                                    >
                                                        {t('button.confirm')}
                                                    </AppButton>
                                                    <AppButton
                                                        style={{ margin: '0', width: '100%', marginTop: 10, backgroundColor: 'white', borderColor: '#d0d0d0', color: '#000' }}
                                                        className="btn btn-warning"
                                                        color="warning"
                                                        // variant="contained"
                                                        // color="primary"
                                                        type="button"
                                                        onClick={onCancel}
                                                    >
                                                        {t("button.cancelOrder")}
                                                    </AppButton>
                                                </div>
                                            </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>
                                {/* info price */}
                                <div style={Style.containerCenter}>
                                    <div>
                                        <Row>
                                            <Col span={24}><hr style={{ borderTop: '1px solid ' }}/></Col>
                                            <Col span={16} className="mb-2">
                                                <span >{t('label.monthlyCost')}: </span>
                                            </Col>
                                            <Col span={8} className="mb-2" style={{ textAlign: 'right' }}>
                                                <span>{values.price}</span>
                                            </Col>
                                            <Col span={16} className="mb-2">
                                                <span style={Style.discountPrice}>{t('label.discountAmount')}:</span>
                                            </Col>
                                            <Col span={8} className="mb-2" style={{ textAlign: 'right' }}>
                                                <span style={Style.discountPrice}>{`- ${values.discountPrice}`}</span>
                                            </Col>
                                            <Col span={16} className="mb-2">
                                                <span >{t('label.totalAmount')}: </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.consumptionTax', { 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={{ fontWeight: 'bold' }}>{`${t('label.toalPaymentAmount')}: `}</span>
                                            </Col>
                                            <Col span={8} className="mb-2" style={{ textAlign: 'right', fontWeight: 'bold' }}>
                                                <span>{values.totalPayment}</span>
                                            </Col>
                                            <Col span={24}><hr style={{ borderTop: '1px solid ' }} /></Col>
                                            {initValues.numberFreeTerm && parseInt(initValues.numberFreeTerm) !== 0 ? <Col span={24}>
                                            {t('text.confirmFreePeriod', { freePeriod: initValues.numberFreeTerm && parseInt(initValues.numberFreeTerm) !== 0 ? initValues.numberFreeTerm : '' })}
                                            </Col> : <></>}
                                            <Col span={24}>
                                            <Col span={24}>{t('text.annualAmount', { amount: formatThousandsNumber(initValues.costForOneYear) })}</Col>
                                            <Col span={24}>{t('text.annualAmount2')}</Col>
                                            </Col>
                                        </Row>
                                        <div className="text-right mt-4" style={{ ...Style.containerCenter, flexDirection: 'column' }}>
                                            <AppButton
                                                style={{ width: '100%', backgroundColor: '#00B27B', borderColor: '#00B27B' }}
                                                className="btn btn-info mr-1"
                                                disabled={isCouponUserDetailLoad}
                                                type="submit"
                                            >
                                                {t('button.confirm')}
                                            </AppButton>
                                            <AppButton
                                                style={{ margin: '0', width: '100%', marginTop: 10, backgroundColor: '#E44A4A', borderColor: '#d0d0d0', color: '#ffffff' }}
                                                className="btn btn-warning"
                                                color="warning"
                                                type="button"
                                                onClick={onCancel}
                                            >
                                                {t("button.cancelOrder")}
                                            </AppButton>
                                        </div>
                                    </div>
                                </div>
                                </Col>
                            }
                        </Row>
                    </div>
                </FormWrapper>
            </Fragment>
        </div>
    );
};


