import { useCallback, useEffect, useMemo } from 'react';

import { FormInstance } from 'antd';
import { useTranslation } from 'react-i18next';
import { useSearchParams } from 'react-router-dom';

import { PayUrlShowType } from '@/defines';
import { useLoginDialog } from '@/hooks/useLoginDialog';
import { dialogModel } from '@/models/dialogModel';
import { fetchGetUserConfig, fetchPayOrderCreate } from '@/services/config';
import { message } from '@/utils/antdAppInstance';
import { isAuthenticated } from '@/utils/authUtils';
import { decryptUrlParams } from '@/utils/requestCrypto';

import { PayQrContent } from './components/OrderSummary/PayQrContent';
import { PayWaitingContent } from './components/OrderSummary/PayWaitingContent';

import type { Plan } from './useService';

const ORDER_TYPE_PLAN = 1;

type PayOrder = { orderId: string; payUrl: string; showType: PayUrlShowType };

export interface UseActionReturn {
    handlePayNow: (plan: Plan, payMethod: string) => void;
}

function useQrPayDialog() {
    const { t } = useTranslation();
    const { openDialog, closeDialog } = dialogModel.useModel();

    const onPaymentSuccess = useCallback(() => {
        return fetchGetUserConfig({}).then(() => {
            message.success(t('pages.pricing.payFlow.planPurchaseSuccess'));
        });
    }, [t]);

    return useCallback(
        (order: PayOrder) => {
            const qrDialogId = openDialog({
                title: t('pages.pricing.payFlow.waitingTitle'),
                content: (
                    <PayQrContent
                        orderId={order.orderId}
                        payUrl={order.payUrl}
                        onClose={() => closeDialog(qrDialogId)}
                        onPaymentSuccess={onPaymentSuccess}
                    />
                ),
                buttons: [
                    {
                        label: t('pages.pricing.payFlow.closeWaiting'),
                        variant: 'secondary' as const,
                        onClick: (_e: React.MouseEvent<HTMLButtonElement>, dialogId: string) => {
                            closeDialog(dialogId);
                        },
                    },
                ],
                maskClosable: false,
                closeable: true,
            });
        },
        [t, openDialog, closeDialog, onPaymentSuccess]
    );
}

function useJumpToPayDialog() {
    const { t } = useTranslation();
    const { openDialog, closeDialog } = dialogModel.useModel();

    const onPaymentSuccess = useCallback(() => {
        return fetchGetUserConfig({}).then(() => {
            message.success(t('pages.pricing.payFlow.planPurchaseSuccess'));
        });
    }, [t]);

    return useCallback(
        (order: PayOrder) => {
            openDialog({
                title: t('pages.pricing.payFlow.goToPayTitle'),
                content: (
                    <p className="text-white/90 text-sm leading-[1.43]">
                        {t('pages.pricing.payFlow.goToPayDesc')}
                    </p>
                ),
                buttons: [
                    {
                        label: t('pages.pricing.payFlow.goToPayButton'),
                        variant: 'primary' as const,
                        onClick: (_e: React.MouseEvent<HTMLButtonElement>, dialogId: string) => {
                            window.open(order.payUrl, '_blank');
                            closeDialog(dialogId);
                            const waitId = openDialog({
                                title: t('pages.pricing.payFlow.waitingTitle'),
                                content: (
                                    <PayWaitingContent
                                        orderId={order.orderId}
                                        onClose={() => closeDialog(waitId)}
                                        onPaymentSuccess={onPaymentSuccess}
                                    />
                                ),
                                buttons: [
                                    {
                                        label: t('pages.pricing.payFlow.closeWaiting'),
                                        variant: 'secondary' as const,
                                        onClick: (
                                            _e: React.MouseEvent<HTMLButtonElement>,
                                            d: string
                                        ) => {
                                            closeDialog(d);
                                        },
                                    },
                                ],
                                maskClosable: false,
                            });
                        },
                    },
                ],
                maskClosable: false,
                closeable: true,
            });
        },
        [t, openDialog, closeDialog, onPaymentSuccess]
    );
}

export interface UseActionParams {
    form: FormInstance<{ planId: string; payMethod: string }>;
    plans: Plan[];
}

export function useAction(params?: UseActionParams): UseActionReturn {
    const form = params?.form;
    const plans = useMemo(() => params?.plans ?? [], [params?.plans]);
    const [searchParams] = useSearchParams();
    const openLoginDialog = useLoginDialog();
    const openQrPayDialog = useQrPayDialog();
    const openJumpToPayDialog = useJumpToPayDialog();

    useEffect(() => {
        if (!form || plans.length === 0) return;
        const encrypted = searchParams.get('d');
        if (encrypted) {
            decryptUrlParams<{ planId: string }>(encrypted).then((decrypted) => {
                const id = decrypted?.planId;
                if (id && plans.some((p) => p.id === id)) {
                    form.setFieldsValue({ planId: id });
                    return;
                }
                const defaultPlan = plans.find((p) => p.isDefault);
                if (defaultPlan) form.setFieldsValue({ planId: defaultPlan.id });
            });
            return;
        }
        const defaultPlan = plans.find((p) => p.isDefault);
        if (defaultPlan) {
            form.setFieldsValue({ planId: defaultPlan.id });
        }
    }, [form, plans, searchParams]);

    const handlePayNow = useCallback(
        (selectedPlan: Plan, selectedPayMethod: string) => {
            if (!isAuthenticated()) {
                openLoginDialog({
                    titleKey: 'pages.pricing.payFlow.loginTitle',
                    promptKey: 'pages.pricing.payFlow.loginPrompt',
                });
                return;
            }

            // 创建订单
            fetchPayOrderCreate({
                orderType: ORDER_TYPE_PLAN,
                payType: selectedPayMethod,
                channelItemId: selectedPlan.id,
            })
                .then((res) => {
                    const order = res?.data?.userPayOrder;
                    if (!order?.payUrl || !order?.orderId) return;

                    if (order.showType === PayUrlShowType.SHOW_QR_CODE) {
                        // 如果订单支付地址的显示类型为二维码，则打开二维码支付对话框
                        openQrPayDialog(order);
                        return;
                    }
                    // 如果订单支付地址的显示类型为跳转，则跳转到支付地址并打开等待支付对话框
                    openJumpToPayDialog(order);
                })
                .catch(() => {});
        },
        [openLoginDialog, openQrPayDialog, openJumpToPayDialog]
    );

    return {
        handlePayNow,
    };
}
