import styles from "./styles.module.scss";
import React, { useEffect, useRef, useState } from 'react';
import { useNavigate } from "react-router-dom";
import { useLocation, useOrientation } from "react-use";
import { localStorageGet } from "@utils/helpers";
import { LOCAL_GAME_URL, LOCAL_SIGN } from "@constants/localkey";
import { ReactComponent as Boxbg } from '@assets/singlesvg/back/boxbg.svg';
import { ReactComponent as Boxclose } from '@assets/singlesvg/back/boxclose.svg';
import { ReactComponent as Circlebg } from '@assets/singlesvg/back/circlebg.svg';
import { ReactComponent as Circlearrow } from '@assets/singlesvg/back/circlearrow.svg';
import LoadingScreen from "@components/LoadingScreen";
import { ROUTE_PATH } from "@constants/routes";
import { useDispatch, useSelector } from "react-redux";
import { reqGameCardInfo } from "@features/api";
import { getHallConnState } from "@features/socketSlice";
import Draggable from 'react-draggable';
import useGameIFrame from "@hooks/useGameIFrame";
import { getFreeWithdraw, getGameCardInfo, getUserInsureScore, getUserVip } from "@features/mainSlice";
import { useThemeProvider } from "@contexts/themeContext"; // The default
import UnlockWithdrawBox from "@widgets/UnlockWithdrawBox";
import WGameWithdrawTips from "@widgets/WGameWithdrawTips";
import WGameMenu from "./WGameMenu/WGameMenu";
const i18n = global.i18n;

const DelayTimes = 10000;

const WGame = () => {
    const dispatch = useDispatch();
    const { gameID, preLocation, openService } = useThemeProvider();
    const gameid = gameID;
    const [openBox, setOpenBox] = useState(false);
    const isConnected = useSelector(getHallConnState);
    const [gameURL, setGameURL] = useState("");
    const navigate = useNavigate();
    const backBoxRef = useRef(null);
    const [dragDeltaY, setDragDeltaY] = useState(0);
    const { isGameLoad, forceLandscape, setIsGameLoad, iFrameRef, setExtBackFunc, handleEnterGame } = useGameIFrame();
    const gameCardInfo = useSelector(getGameCardInfo(gameid));
    const insureScore = useSelector(getUserInsureScore);
    const freeWithdraw = useSelector(getFreeWithdraw);
    const totalMoney = freeWithdraw.total;
    const [curMoney, setCurMoney] = useState(0);

    const [openBonusbox, setOpenBonusbox] = useState(false);
    const bonusBoxTimer = useRef(null);
    const bonusBoxUpdater = useRef(null);
    const openBonusboxRef = useRef(false);
    const curMoneyRef = useRef(0);
    const lastBonusRef = useRef(0);
    const firstOpenRef = useRef(false);

    const menuDelayTimer = useRef(null);
    const [showMenu, setShowMenu] = useState(true);
    const vip = useSelector(getUserVip);

    const onBack = () => {
        // dispatch(reqGameInfo());
        let ppath = ROUTE_PATH.HOME;
        if (preLocation != null) {
            let pathname = preLocation.pathname;
            if (pathname != null && pathname !== "") {
                if (!pathname.startsWith(ROUTE_PATH.GAME)) {
                    ppath = pathname;
                }
            }
        }
        // navigate(ROUTE_PATH.BACK);
        navigate(ppath, { replace: true });
    }

    const parseURL = () => {
        let key = LOCAL_GAME_URL + gameid;
        let sign = localStorageGet(LOCAL_SIGN);
        // let url=localStorageGet(key);
        let url = gameCardInfo.link;
        if (gameCardInfo.level > 0) url += "&level=" + gameCardInfo.level;
        if (url == null) return;
        if (url.indexOf("?") === -1) url = url + "?sign=" + sign;
        else url = url + "&sign=" + sign;
        setGameURL(url);
        // gameURL=url;
    }

    const openBonusTips = () => {
        if (curMoney >= totalMoney) {
            /// 可提现
            global.showGameWithdrawTips(3);
            // adjust 点击可提现按钮(已解锁)
            global.tracker.trackEvent("click_withdraw_unlock");
            global.tracker.trackEvent("click_withdraw_unlock_count");
        } else {
            /// 未达到
            global.showGameWithdrawTips(2);
            // adjust 点击可提现按钮(未解锁)
            global.tracker.trackEvent("click_withdraw_lock");
            global.tracker.trackEvent("click_withdraw_lock_count");
        }
    }

    const openMsgBox = () => {
        if (curMoney < totalMoney) {
            /// 未满足提现金额
            global.showGameWithdrawTips(1);
            return;
        }

        let data = {
            title: i18n.t("game.msg_title"),
            content: i18n.t("game.msg_content"),
            cancelCB: (click) => { click && onBack(); },
            sureLabel: i18n.t("game.cancel"),
            cancelLabel: i18n.t("game.back")
        }
        global.msgBoxShow(data);
    }

    const clearBonusBoxTimer = () => {
        if (bonusBoxTimer.current != null) {
            clearTimeout(bonusBoxTimer.current);
            bonusBoxTimer.current = null;
        }
    }

    const clearMenuDelayTimer = () => {
        if (menuDelayTimer.current != null) {
            clearTimeout(menuDelayTimer.current);
            menuDelayTimer.current = null;
        }
    }

    const clearBonusBoxUpdater = () => {
        if (bonusBoxUpdater.current != null) {
            clearTimeout(bonusBoxUpdater.current);
            bonusBoxUpdater.current = null;
        }
    }

    const updateWithdrawAmount = (money) => {
        setCurMoney(money);

        if (money >= totalMoney && !firstOpenRef.current) {
            firstOpenRef.current = true;
            global.showGameWithdrawTips(3);
            // adjust 游戏内引导提款弹窗
            global.tracker.trackEvent("enter_withdraw_panel");
            global.tracker.trackEvent("enter_withdraw_panel_count");
        }
    }

    const showBonusBox = () => {
        if (vip > 0) return;
        setOpenBonusbox(true);
    }

    const onUpdateGameScore = (golds) => {
        let new_golds = (golds / global.CASH_BASE).toFixed(2);
        const money = lastBonusRef.current;
        lastBonusRef.current = new_golds;

        clearBonusBoxTimer();
        if (!openBonusboxRef.current) {
            openBonusboxRef.current = true;
            showBonusBox();
            updateWithdrawAmount(new_golds);
            return;
        }

        updateWithdrawAmount(money);
    }

    useEffect(() => {
        if (Number(gameid) > 0 && gameCardInfo == null) {
            dispatch(reqGameCardInfo(gameid));
        }
        if (iFrameRef != null) {
            iFrameRef.extBackFunc = () => {
                onBack();
            }
        }

        global.clearPopupFlow();
        // menuDelayTimer.current = setTimeout(() => {
        //     setShowMenu(true);
        // }, DelayTimes);

        return () => {
            global.onUpdateGameScore = null;
            clearBonusBoxTimer();
            clearMenuDelayTimer();
            clearBonusBoxUpdater();
        };
    }, []);

    useEffect(() => {
        if (!freeWithdraw || !freeWithdraw.state) return;

        // bonusBoxTimer.current = setTimeout(() => {
        //     setOpenBonusbox(true);
        // }, DelayTimes);

        //const insureScore = freeWithdraw.InsureScore;

        if (freeWithdraw.state === 1) {
            setCurMoney(insureScore);
            lastBonusRef.current = insureScore;
            global.onUpdateGameScore = (golds) => {
                setShowMenu(true);
                onUpdateGameScore(golds);
            }
        } else {
            //不需要更新
            setCurMoney(totalMoney);
            lastBonusRef.current = totalMoney;
            global.onUpdateGameScore = (golds) => {
                setShowMenu(true);
                showBonusBox();
            }
        }
    }, [freeWithdraw])

    useEffect(() => {
        if (!isConnected) {
            setIsGameLoad(false);
        }
    }, [isConnected])

    useEffect(() => {
        if (gameCardInfo != null) {
            parseURL();
        }
    }, [gameCardInfo])

    useEffect(() => {
        openBonusboxRef.current = openBonusbox;
    }, [openBonusbox])

    useEffect(() => {
        curMoneyRef.current = curMoney;
    }, [curMoney])

    const renderBackBox = () => {
        if (!showMenu) return <></>;
        return (
            <Draggable
                axis="y"
                bounds="parent"
                onStart={(e, ui) => {
                    setDragDeltaY(ui.y);
                }}
                onStop={(e, ui) => {
                    setDragDeltaY(Math.abs(ui.y - dragDeltaY));
                }}
            >
                <div className={`${styles.dragbox}`}>
                    <div ref={backBoxRef} className={`${styles.backbox} ${openBox ? styles.open : styles.close}`}
                        onClick={() => {
                            setOpenBox(!openBox);
                        }}
                        onTouchEnd={(e) => {
                            if (dragDeltaY < 5) {
                                setOpenBox(!openBox);
                            }
                        }}>
                        <button className={styles.back_btn}>
                            <Circlebg className={styles.back_bg} />
                            <Circlearrow className={`${styles.arrow} ${openBox ? styles.a_open : styles.a_close}`} />
                        </button>
                        <button className={styles.close_box} onClick={() => {
                            openMsgBox();
                        }} onTouchEnd={() => {
                            openMsgBox();
                        }}>
                            <Boxbg className={styles.bg} />
                            <div className={styles.close_info}>
                                <div>{i18n.t("game.back")}</div>
                                <div className={styles.line}></div>
                                <Boxclose className={styles.close}></Boxclose>
                            </div>
                        </button>
                    </div>
                </div>
            </Draggable>
        )
    }

    const renderGame = () => {
        return (
            <iframe
                ref={iFrameRef}
                id={"game"}
                title={"game"}
                src={gameURL}
                // src={"https://j15.gamej15.top/pwa.html"}
                className={styles.content}
                allow="fullscreen"
                sandbox='allow-scripts allow-same-origin allow-popups allow-top-navigation allow-top-navigation-by-user-activation'
            >
            </iframe>
        )
    }

    const renderBonusbox = () => {
        if (!openBonusbox) return <></>;
        return (
            <UnlockWithdrawBox onClick={openBonusTips} current={curMoney} total={totalMoney} landscape={forceLandscape} />
        )
    }

    const renderPopup = () => {
        return (
            <>
                <WGameWithdrawTips onLeave={onBack} currentAmount={curMoney} totalAoumt={totalMoney} forceLandscape={forceLandscape} />
            </>
        )
    }

    const renderLoading = () => {
        if (isGameLoad) return (<></>);
        return (
            <div className={styles.loading}>
                <LoadingScreen />
            </div>
        )
    }

    return (
        <>
            <div className={`${styles.container} ${forceLandscape ? "force-landscape" : ""}`}>
                {
                    gameCardInfo == null ? renderLoading() : (
                        <>
                            {
                                isConnected ? (
                                    <>
                                        {renderGame()}
                                        {/* {renderBackBox()} */}
                                        {/* {renderBackBtn()} */}
                                        {/* {renderBonusbox()} */}
                                        {renderPopup()}
                                    </>
                                ) : (<></>)
                            }
                            {renderLoading()}
                        </>
                    )
                }

                <WGameMenu onBack={onBack} onOpenGame={handleEnterGame} />

            </div>

            {renderBonusbox()}
        </>

    )
}
export default WGame;
