import { useEffect, useRef, useState } from "react";
import { ROUTE_PATH } from "@constants/routes";
import { exitFullScreen, isAndroid, isIOS, isLandscape, isPortrait, openFullScreen } from "@utils/helpers";
import { useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { getBankRuptcyGift } from "@features/paySlice";
import { getLandscapeGames, updateGameCardInfo } from "@features/mainSlice";
import { useOrientation } from "react-use";
import { useThemeProvider } from "@contexts/themeContext";
const objInfo = {
    closeCount: 0
}

const useGameIFrame = () => {
    const iFrameRef = useRef(null);
    const [forceLandscape, setForceLandscape] = useState(false);
    const [isGameLoad, setIsGameLoad] = useState(false);
    const ruptcyGift = useSelector(getBankRuptcyGift);
    const LandscapeGames = useSelector(getLandscapeGames);
    const { gameID } = useThemeProvider();
    const navigate = useNavigate();
    const dispatch = useDispatch();

    const orientation = useOrientation();
    const onBack = () => {
        // dispatch(reqGameInfo());
        if (iFrameRef.extBackFunc != null) {
            iFrameRef.extBackFunc();
            return;
        }
        navigate(ROUTE_PATH.BACK);
    }
    const checkCloseCount = () => {
        if (objInfo.closeCount >= 2) {
            onBack();
        }
    }
    const safeNavigate = (route, options) => {
        if (isIOS()) {
            window.location.href = route;
        } else {
            navigate(route, options)
        }
    }
    const receiveMessage = (event) => {
        let data = event.data;
        //console.log(data);
        if (data && data.cmd != null) {
            // toast.success(JSON.stringify(data))
            if (data.cmd === "back") {
                onBack();
            }
            else if (data.cmd === "pay") {
                if (!!ruptcyGift && ruptcyGift.length > 0) {
                    global.showExclusiveGift();
                } else {
                    safeNavigate(ROUTE_PATH.DEPOSIT, { replace: true })
                }
            }
            else if (data.cmd === "withdraw") {
                safeNavigate(ROUTE_PATH.SAQUE, { replace: true });
            }
            else if (data.cmd === "fullScreen") {
                openFullScreen();
            }
            else if (data.cmd === "closeLoading") {
                setIsGameLoad(true);
                objInfo.closeCount++;
                checkCloseCount();
            }
        }
    }
    const clearGameTimeout = () => {
        const gameFrame = iFrameRef.current;
        if (gameFrame != null) {
            if (gameFrame.loadtimeout != null) {
                clearTimeout(gameFrame.loadtimeout);
                gameFrame.loadtimeout = null;
            }
        }
    }
    const handleLoadGame = () => {
        setIsGameLoad(true);
        clearGameTimeout();
    }
    const initGameEvent = () => {
        const gameFrame = iFrameRef.current;
        if (gameFrame != null) {
            openFullScreen();
            gameFrame.addEventListener('load', handleLoadGame);
            gameFrame.loadtimeout = setTimeout(() => {
                handleLoadGame();
            }, 5000);
        }
        window.addEventListener("message", receiveMessage, false);
        objInfo.closeCount = 0;
    }
    const removeGameEvent = () => {
        const gameFrame = iFrameRef.current;
        if (gameFrame != null) {
            gameFrame.removeEventListener('load', handleLoadGame);
            clearGameTimeout();
        }
        window.removeEventListener("message", receiveMessage);
        objInfo.closeCount = 0;
    }
    const handleEnterGame = (data) => {
        objInfo.closeCount = 0;
        setIsGameLoad(false);
        let id = data.id;
        let url = data.link;
        dispatch(updateGameCardInfo({
            data: data,
            level: 0
        }))
        let path = ROUTE_PATH.GAME + "/" + id;
        global.authLockPath = path;
        navigate(path);
    }
    useEffect(() => {
        //openFullScreen();
        initGameEvent();
        return () => {
            removeGameEvent();
            exitFullScreen();
        };
    }, [iFrameRef.current]);

    useEffect(() => {
        const landscape = isLandscape(orientation);
        document.documentElement.style.setProperty('--view-size', landscape ? 0.5 : 1);
        if (landscape) setForceLandscape(false);
        if (landscape || window.innerWidth >= window.innerHeight) {
            document.documentElement.classList.add("landscape-page");
        } else {
            document.documentElement.classList.remove("landscape-page");
        }

        return () => {
            document.documentElement.style.setProperty('--view-size', 1);
            document.documentElement.classList.remove("landscape-page");
        }
    }, [orientation]);

    useEffect(() => {
        if (gameID == 0) return;

        const ios = isIOS();
        const isMobile = isAndroid() || ios;
        const portrait = isPortrait();
        const index = LandscapeGames.indexOf(gameID);
        if (index === -1 || !isMobile || !portrait) {
            return;
        }

        setForceLandscape(true);
        document.documentElement.style.setProperty('--view-size', 0.9);
        if (isIOS()) {
            document.documentElement.style.setProperty('--landscape-ios', "10vh");
        }

        return () => {
            document.documentElement.style.setProperty('--landscape-ios', "0vh");
        }


        // document.documentElement.classList.add("landscape-page");
        // document.documentElement.classList.add("force-landscape");
        // document.documentElement.style.setProperty('--view-size', 0.5);

        // if (ios) {
        //     document.documentElement.classList.add("force-landscape-ios");
        // }
        // return () => {
        //     document.documentElement.classList.remove("force-landscape");
        // }
    }, [gameID])
    return {
        iFrameRef,
        isGameLoad,
        forceLandscape,
        safeNavigate,
        setIsGameLoad,
        handleEnterGame,
    };
}
export default useGameIFrame;
