import { useEffect, useRef } from 'react';

import { useTranslation } from 'react-i18next';

import { PayOrderStatus } from '@/defines';
import { fetchPayOrderStatus } from '@/services/config';

const POLL_INTERVAL_MS = 2500;

export interface PayWaitingContentProps {
    orderId: string;
    onClose: () => void;
    /** 支付成功时调用（刷新用户数据、提示等），随后会调用 onClose */
    onPaymentSuccess?: () => void | Promise<void>;
}

export function PayWaitingContent({ orderId, onClose, onPaymentSuccess }: PayWaitingContentProps) {
    const { t } = useTranslation();
    const timerRef = useRef<ReturnType<typeof setInterval> | null>(null);

    useEffect(() => {
        const poll = () => {
            fetchPayOrderStatus({ orderId })
                .then(async (res) => {
                    const state = res?.data?.orderState;
                    if (state === PayOrderStatus.PAID || state === PayOrderStatus.FAILED) {
                        if (timerRef.current) {
                            clearInterval(timerRef.current);
                            timerRef.current = null;
                        }
                        if (state === PayOrderStatus.PAID && onPaymentSuccess) {
                            await Promise.resolve(onPaymentSuccess());
                        }
                        onClose();
                    }
                })
                .catch(() => {});
        };

        poll();
        timerRef.current = setInterval(poll, POLL_INTERVAL_MS);

        return () => {
            if (timerRef.current) {
                clearInterval(timerRef.current);
            }
        };
    }, [orderId, onClose, onPaymentSuccess]);

    return (
        <p className="text-white/90 text-sm leading-[1.43]">
            {t('pages.pricing.payFlow.waitingDesc')}
        </p>
    );
}
