import { createContext, useContext, useEffect, useState } from 'react';
import { isRtlLang } from 'rtl-detect';
import { useWindowSize } from "react-use";
import { APP_THEME } from "@constants/app";
import { ROUTE_PATH } from "@constants/routes";
import { useSelector } from "react-redux";
import { getFreeWithdraw, getreRecommendGame, getServiceLink, getUserInfo, isLogined } from "@features/mainSlice";
import SoundHelp from "@utils/SoundManger";
import usePreviousRoute from "@hooks/usePreviousRoute";
import { useNavigate } from 'react-router';
import { useWithdrawMission } from './withdrawMissionContext';
import { localStorageSet } from '@utils/helpers';
import { getFirstPayGift } from '@features/paySlice';

const ThemeContext = createContext(undefined);

export const ThemeProvider = ({ children }) => {
    const { height } = useWindowSize();
    const width = 375;
    const page = document.documentElement;
    const isRtl = isRtlLang(navigator.language);
    const browserTheme = window.matchMedia('(prefers-color-scheme: light)');
    const persisted = JSON.parse(localStorage.getItem('preferences') || '{}');
    const isDesktop = () => {
        return width >= 1280;
    };
    const isTablet = () => {
        return width < 1280 && width >= 768;
    };
    const isMobile = () => {
        return width < 768;
    };
    const getMFontScale = () => {
        let base = 0.88;
        let baseWidth = 390;
        let ratio = width / 390;
        let scale = Number((base * ratio).toFixed(2));
        return scale;
    };
    const [theme, setTheme] = useState(persisted && persisted.theme ? persisted.theme : (APP_THEME.DARK));
    // const [fontScale, setFontScale] = useState(persisted.fontScale || 1);
    const [fontScale, setFontScale] = useState(isMobile() ? getMFontScale() : 1);
    const [direction, setDirection] = useState(persisted.direction || (isRtl ? 'rtl' : 'ltr'));

    const [installOpen, setInstallOpen] = useState(persisted && (persisted.installOpen != null) ? persisted.installOpen : true);

    const [soundOpen, setSoundOpen] = useState(persisted && (persisted.soundOpen != null) ? persisted.soundOpen : true);

    const [headerHeight, setHeaderHeight] = useState('64px');

    //GameSearch
    const [isShowSearch, setIsShowSearch] = useState(false);

    const [searchData, setSearchData] = useState(null);

    const [showHeader, setShowHeader] = useState(false);
    const [showMHeader, setShowMHeader] = useState(false);

    //GameSearch

    //lang select
    const [isShowLang, setIsShowLang] = useState(false);

    //show pass prompt
    const [isShowPassPrompt, setIsShowPassPrompt] = useState(false);

    //show wheel
    const [isShowWheel, setIsShowWheel] = useState(false);

    //show wd pass box
    const [isShowWDPassBox, setIsShowWDPassBox] = useState(false);
    const [isOpenSub, setIsOpenSub] = useState(false);
    const isLogin = useSelector(isLogined);
    const user = useSelector(getUserInfo);
    const recommendGame = useSelector(getreRecommendGame);
    const serviceLink = useSelector(getServiceLink);
    const firstPayGift = useSelector(getFirstPayGift);

    const { preLocation, gameID } = usePreviousRoute();
    const [welfTabState, setWelfTabState] = useState(-1);
    const navigate = useNavigate();

    const initWindowSize = () => {
        if (isMobile()) global.device = "m";
        else global.device = "d";
        global.width = width;
        global.height = height;
        changeFontScale(isMobile() ? getMFontScale() : 1);
    };
    // initWindowSize();
    const stopTransition = () => {
        page.classList.add('no-transition');
        setTimeout(() => page.classList.remove('no-transition'), 100);
    };

    const savePreferences = () => {
        localStorage.setItem('preferences', JSON.stringify({
            theme,
            fontScale,
            direction,
            installOpen,
            soundOpen
        }));
    };

    const toggleTheme = () => {
        setTheme(theme === APP_THEME.LIGHT ? APP_THEME.DARK : APP_THEME.LIGHT);
        // stopTransition();
    };

    const changeFontScale = (scale) => {
        setFontScale(scale);
        page.style.setProperty('--font-scale', scale);
        stopTransition();
    };

    const toggleDirection = () => {
        setDirection(direction === 'ltr' ? 'rtl' : 'ltr');
        page.setAttribute('dir', direction);
    };

    const initHeaderHeight = (height) => {
        setHeaderHeight(height);
    };

    const showGameSearchPanel = (show, data) => {
        setIsShowSearch(show);
        setSearchData(data);
    };
    //检查提现
    const checkWithdraw = () => {
        if (isLogin) {
            if (user) {
                let InsurePass = Number(user.InsurePass);
                if (InsurePass !== 1) {
                    setIsShowPassPrompt(true);
                    return false;
                }
                else {
                    let pass = global.getWDPass();
                    if (pass === "") {
                        setIsShowWDPassBox(true);
                        return false;
                    }
                }
            }
        }
        return true;
    };
    //检查路由是否允许跳转
    const checkRoute = (path) => {
        // if (path===ROUTE_PATH.SAQUE){
        //     return checkWithdraw();
        // }
        return true;
    };
    const toggleInstallOpen = () => {
        setInstallOpen(!installOpen);
    };
    const toggleSoundOpen = () => {
        setSoundOpen(!soundOpen);
    };

    const openRecommandGamePopup = () => {
        global.recommendedGames && global.recommendedGames.show();
    };

    const openRecommandGame = (popup = false) => {
        if (recommendGame.startsWith(ROUTE_PATH.GAME)) {
            navigate(recommendGame);
        } else {

        }
        navigate(recommendGame);
        console.error("recommendGame", recommendGame);
    };

    const openService = () => {
        window.open(serviceLink);
    };

    const handleRoutes = (route, pathname) => {
        if (route === ROUTE_PATH.PAY) {
            navigate(ROUTE_PATH.DEPOSIT);
            // adjust 设置充值类型
            global.enterRechargeType = 0;
            return true;
        }

        if (route === ROUTE_PATH.SAQUE) {
            navigate(ROUTE_PATH.WITHDRAW);
            return true;
        }

        if (pathname.startsWith(ROUTE_PATH.GAME)) {
            window.location.hash = "";
            navigate(ROUTE_PATH.HOME + route, { replace: true });
            return true;
        }

        return false;
    };

    const openFirstDeposit = () => {
        if (!firstPayGift || firstPayGift.has_purchased) {
            navigate(ROUTE_PATH.DEPOSIT);
            return;
        }

        navigate(ROUTE_PATH.FIRSTDEPOSIT);
    };

    const hasFirstPayGift = () => {
        if (!firstPayGift || firstPayGift.has_purchased) {
            return false;
        }
        return true;
    };

    global.openFirstDeposit = openFirstDeposit;

    useEffect(() => {

        // page.style.setProperty('--font-scale', fontScale);
        // page.style.setProperty('--widget-scale', fontScale === 1 ? '0px' : `${fontScale * 3}px`);
        page.setAttribute('dir', direction);
        savePreferences();
        SoundHelp.setSoundOn(soundOpen);

        // window
        //     .matchMedia('(prefers-color-scheme: light)')
        //     .addEventListener('change', event => {
        //         event.matches ? setTheme('light') : setTheme('dark');
        //         stopTransition();
        //         savePreferences();
        //     })
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [theme, fontScale, direction, installOpen, soundOpen]);
    useEffect(() => {
        initWindowSize();
    }, [width]);

    global.openRecommandGame = openRecommandGame;
    global.openRecommandGamePopup = openRecommandGamePopup;

    global.openFixedWithdraw = (payload) => {
        // console.error("openFixedWithdraw", payload);
        // localStorageSet('fixedScore', score);
        global.referralPayload = payload;
        navigate(ROUTE_PATH.REFERRAL);
    };

    const freeWithdraw = useSelector(getFreeWithdraw);
    const checkShowFreeWithdraw = () => {
        const score = user?.InsureScore;
        if (freeWithdraw?.state === 4 && score < 20) {
            return false;
        } else {
            return true;
        }
    };

    return (
        <ThemeContext.Provider
            value={{
                theme,
                fontScale,
                direction,
                toggleTheme,
                changeFontScale,
                toggleDirection,
                isDesktop,
                isTablet,
                isMobile,
                headerHeight,
                initHeaderHeight,
                isShowSearch,
                searchData,
                showGameSearchPanel,
                showHeader,
                setShowHeader,
                showMHeader,
                setShowMHeader,
                //lang
                isShowLang,
                setIsShowLang,
                isShowPassPrompt,
                setIsShowPassPrompt,
                //检查路由是否允许跳转
                checkRoute,
                isShowWheel,
                setIsShowWheel,
                installOpen,
                toggleInstallOpen,
                isShowWDPassBox,
                setIsShowWDPassBox,
                //是否打开sub
                isOpenSub,
                setIsOpenSub,
                //sound
                soundOpen,
                toggleSoundOpen,
                //preroute hook
                preLocation,
                gameID,
                welfTabState,
                setWelfTabState,
                openRecommandGame,
                openRecommandGamePopup,
                openService,
                handleRoutes,
                openFirstDeposit,
                hasFirstPayGift,
                checkShowFreeWithdraw
            }}>
            {children}
        </ThemeContext.Provider>
    );
};

export const useThemeProvider = () => useContext(ThemeContext);
