import LoadingScreen from "@components/LoadingScreen";
import styles from './styles.module.scss';
import { useEffect, useRef, useState } from "react";
import { useSelector } from "react-redux";
import { getCurrPayOrder } from "@features/paySlice";
import { useNavigate } from "react-router";
import { ROUTE_PATH } from "@constants/routes";
import useVisibilityChange from "@hooks/useVisibilityChange";

const WPayIFrame = () => {
    const [isLoading, setIsLoading] = useState(true);
    const orderInfo = useSelector(getCurrPayOrder);
    const statusRef = useRef(null);
    const checkTimer = useRef(null);
    const payUrl = global.curPayUrl;
    const navigate = useNavigate();
    useVisibilityChange((visible, duration) => {
        if (visible !== 1 && checkTimer.current != null) {
            clearTimeout(checkTimer.current);
            return;
        }

        if (checkTimer.current != null) {
            clearTimeout(checkTimer.current);
            checkTimer.current = null;
        }


        if (visible && duration > 2000 && statusRef.current !== 'success') {
            checkTimer.current = setTimeout(() => {
                navigate(ROUTE_PATH.ORDERCHECK);
            }, 500);
        }
    });

    // useEffect(() => {
    //     if (orderInfo == null) return;
    //     if (orderInfo.status == "success" && orderInfo.status != statusRef.current) {
    //         navigate(ROUTE_PATH.HOME, { replace: true });
    //     }
    //     statusRef.current = orderInfo.status;
    // }, [orderInfo])
    return (
        <div className={styles.container}>
            <iframe
                id={"deposit"}
                title={"deposit"}
                src={payUrl}
                className={styles.content}
                allow="fullscreen"
                sandbox='allow-scripts allow-same-origin allow-popups allow-top-navigation allow-top-navigation-by-user-activation'
                onLoad={() => { setIsLoading(false) }}
            >
            </iframe>
            {
                isLoading && <LoadingScreen fill />
            }
        </div>
    )
}

export default WPayIFrame;