import { useDispatch, useSelector } from "react-redux";
import { getFetchStatus, getModules } from "@features/pageSlice";
import { useThemeProvider } from "@contexts/themeContext";
import { Fragment, Suspense, useEffect } from "react";
import { reqPageModules } from "@features/api";
import { REQ_STATUS } from "@api/config";
import LoadingScreen from "@components/LoadingScreen";
import AllWidgets from "@widgets/index";
import styles from "./styles.module.scss";
import BreadCrumb from "@layout/BreadCrumb";
import Spring from "@components/Spring";
import LoadingIn from "@components/Loading/LoadingIn";
import SidebarTrigger from '@ui/SidebarTrigger';
import Logo from '@components/Logo';
import { useNavigate } from "react-router-dom";
import { ROUTE_PATH } from "@constants/routes";
import { numFormatter, sleep } from "@utils/helpers";
import LazyImgix from "@components/Imgix/LazyImgix";
import Button from "@mui/material/Button";
import Footer from "@layout/Footer";
import vip0 from '@assets/vip/0.png';
import vip from '@assets/vip/vip.png';
import mailIcon from '@assets/userinfo/mail.png';
import plus from '@assets/userinfo/plus.png';
import bonus from '@assets/userinfo/bonus.svg';
import HomeWithdraw from "@widgets/HomeWithdraw";
import { useState, useRef, useCallback } from "react";
import symbol from "@assets/symbol-defs.svg";
import ReactImgix, { buildURL } from "react-imgix";
import Sidebar2 from "@layout/Sidebar2";

import vip_symbol from '@assets/vip/symbol.svg';

import {
    getUserInfo,
    isLogined
} from "@features/mainSlice";
import { getFirstPayGift } from "@features/paySlice";
const i18n = global.i18n;

const ModuleGroup = ({ pageID }) => {
    const dispatch = useDispatch();
    const status = useSelector(getFetchStatus);
    const modules = useSelector(getModules(pageID));
    const { isMobile, openFirstDeposit, hasFirstPayGift, checkShowFreeWithdraw } = useThemeProvider();
    const navigate = useNavigate();

    useEffect(() => {
        if (modules == null || modules.length === 0) {
            dispatch(reqPageModules(pageID));
        }
    }, [pageID]);

    const [showWithdrawPopup, setShowWithdrawPopup] = useState(false);
    const firstPayGift = useSelector(getFirstPayGift);
    const user = useSelector(getUserInfo);

    const WithdrawPopup = ({ open, onClose }) => {
        const [isClosing, setIsClosing] = useState(false);

        const handleClose = () => {
            setIsClosing(true);
            setTimeout(() => {
                setIsClosing(false);
                onClose();
            }, 100); // 动画时长 300ms
        };
        const handleClickWithdraw = () => {
            // navigate(ROUTE_PATH.FREEWITHDRAW);
            setShowWithdrawPopup(false);
            global.onClickNormalWithdraw && global.onClickNormalWithdraw();
        };

        const handleClickDeposit = () => {
            //navigate(ROUTE_PATH.DEPOSIT);
            openFirstDeposit();

            // adjust 设置充值类型
            global.enterRechargeType = 0;
        };
        const handleClickTip = (type) => {
            const textArr = [];
            if (type == "cash") {
                textArr.push("This is your total balance, which mainly comes from recharges and various bonuses.");
                textArr.push("After successfully completing the deposit, you will become our esteemed VIP, and you will be able to withdraw all the cash you have won in the game.");
            } else {
                textArr.push("Free Bonus is the bonus given by us when you are a free player.");
                textArr.push("You can withdraw it after depositing and reaching the specified betting amount.");
            }
            global.showCommonTextTip(textArr);
        };

        if (!open) return (<></>);


        return (
            <div className={`${styles.withdrawPopup} ${isClosing ? styles.closing : ''}`} onClick={handleClose}>
                <div className={styles.content} onClick={(e) => e.stopPropagation()}>
                    <div className={`${styles.containBox} ${styles.cashBalance}`}>
                        <div className={styles.top}>
                            <span>Cash Balance</span>

                            <svg className={styles.icon} onClick={() => handleClickTip("cash")}>
                                <use xlinkHref={`${symbol}#icon_question`} />
                            </svg>
                        </div>
                        <div className={styles.bottom}>
                            <div className={styles.value}>$ {user.Score}</div>
                            <div className={styles.right}>
                                <div className={styles.withdraw} onClick={handleClickWithdraw}>Withdraw</div>
                                <div className={styles.plus} onClick={handleClickDeposit}>
                                    <svg className={styles.icon}>
                                        <use xlinkHref={`${symbol}#icon_plus`} />
                                    </svg>
                                </div>

                                {
                                    hasFirstPayGift() && <div className={styles.gift}>
                                        <svg className={styles.icon}>
                                            <use xlinkHref={`${symbol}#icon_gift`} />
                                        </svg>
                                        {firstPayGift?.gift_info.total_bonus}%
                                    </div>
                                }


                            </div>
                        </div>
                    </div>
                    {
                        checkShowFreeWithdraw() ? (<div className={`${styles.containBox} ${styles.freeBonus}`}>
                            <div className={styles.top}>
                                <span>Free Bonus</span>

                                <svg className={styles.icon} onClick={() => handleClickTip("free")}>
                                    <use xlinkHref={`${symbol}#icon_question`} />
                                </svg>
                                {/*  */}
                            </div>
                            <div className={styles.bottom}>
                                <div className={styles.value}>$ {user.InsureScore}</div>
                                <div className={styles.right}>
                                    <div className={styles.withdraw} onClick={handleClickWithdraw}>Withdraw</div>
                                    {/* <div className={styles.plus}>
                            <svg className={styles.icon}>
                                <use xlinkHref={`${symbol}#icon_plus`} />
                            </svg>
                        </div>

                        <div className={styles.gift}>
                            <svg className={styles.icon}>
                                <use xlinkHref={`${symbol}#icon_gift`} />
                            </svg>
                            270%
                        </div> */}

                                </div>
                            </div>
                        </div>) : <></>
                    }

                </div>

                <div className={styles.close} >
                    <svg className={styles.icon}>
                        <use xlinkHref={`${symbol}#icon_close`} />
                    </svg>
                </div>
            </div>
        );
    };

    const UserInfo = () => {
        const isLogin = useSelector(isLogined);
        const navigate = useNavigate();
        // getUserInfo
        // console.error("user", user);
        return (
            <>
                {
                    isLogin ? (
                        // <div className={`d-flex align-items-center ${styles.user_info}`} onClick={() => {
                        //     navigate(ROUTE_PATH.SETTINGS);
                        // }}>
                        //     <div className={styles.info}>
                        //         <div className={styles.nick}>{user.NickName}</div>
                        //         <div className={styles.score}>{global.DOLLAR + " " + numFormatter(user.Score)}</div>
                        //     </div>
                        //     {/*<LazyImage wrapperClassName={styles.avatar} src={user.img} alt={"Head"}/>*/}
                        //     <img className={styles.avatar} src={user.img} alt={"Head"} width={80} />
                        // </div>
                        <div className={styles.userInfo}>
                            <div className={styles.user}>
                                <img className={styles.avatar} src={user.img} alt={"Head"} onClick={() => {
                                    navigate(ROUTE_PATH.SETTINGS);

                                }} />
                                {/* <div className={styles.avatar}></div> */}

                                {/* < img className={styles.vip} src={vip0} alt={"vip"} /> */}
                                <div className={styles.vip}>
                                    <svg className={`${styles.img}`}>
                                        <use xlinkHref={`${vip_symbol}#icon_vip${user.vip == 0 ? "0" : ""}`} />
                                    </svg>
                                    {/* < img src={user.vip == 0 ? vip0 : vip} alt={"vip"} /> */}
                                    <div className={`${styles.level} ${user.vip == 0 ? "" : styles.active}`}>{user.vip}</div>
                                </div>
                            </div>
                            <img src={mailIcon} alt="" className={styles.mail} onClick={() => { navigate(ROUTE_PATH.MESSAGE); }} />
                            <img src={plus} alt="" className={styles.plus} onClick={() => setShowWithdrawPopup(true)} />

                            <div className={styles.wealth}>
                                <div className={styles.cash} id="userScore">${user.Score}</div>
                                <div className={styles.gold}>
                                    {/* <svg className={`${styles.bottomicon}`}>
                                        <use xlinkHref={`${symbol}#TabIcon_Share`} />
                                    </svg> */}
                                    <img src={bonus} alt="" className={styles.bonus} />
                                    <div className={styles.num} id="userInsureScore">{user.InsureScore}</div>
                                </div>
                            </div>

                        </div>
                    ) : (<></>)
                }
            </>
        );
    };
    const MobileSignInUp = () => {
        const navigate = useNavigate();
        const isLogin = useSelector(isLogined);
        return (
            <div className="d-flex align-items-center justify-content-end">
                {
                    !isLogin ? (
                        <>
                            <Button className={`m-button ${styles.btn_sign_in} ${styles.btn_sign_in_mobile}`} onClick={() => {
                                navigate(ROUTE_PATH.SIGN_IN);
                            }}>{i18n.t('sign_in')}</Button>
                            <Button className={`${styles.btn_sign_up} ${styles.btn_sign_up_mobile}`} onClick={() => {
                                navigate(ROUTE_PATH.SIGN_UP);
                            }}>{i18n.t('sign_up')}</Button>
                        </>
                    ) : (
                        <></>
                    )
                }
                {/*<Button  className="m-button">*/}
                {/*    <svg className={"ls-icon"} style={{width:'1.4rem',height:'1.4rem'}}>*/}
                {/*        <use xlinkHref={`${symbol}#icon_Language`} />*/}
                {/*    </svg>*/}
                {/*</Button>*/}
            </div>
        );
    };

    const MobileNav = () => {
        return (
            <div
                className={`d-flex align-items-center justify-content-between ${styles.header} ${styles.header_mobile}`}>
                <div className={`d-flex flex-row flex-1`} style={{ maxWidth: "11rem", marginLeft: "1rem" }}>
                    {/* <SidebarTrigger /> */}
                    <Logo />
                </div>
                <MobileSignInUp />
                <UserInfo />
            </div>
        );
    };
    const topRef = useRef(null);
    // const [containerHeight, setContainerHeight] = useState(0);
    // const containerRef = useCallback((node) => {
    //     if (node !== null) {
    //         // 获取容器高度
    //         const height = node.offsetHeight;
    //         setContainerHeight(height);
    //         console.error("height", height);

    //         // 监听尺寸变化
    //         const resizeObserver = new ResizeObserver(entries => {
    //             for (let entry of entries) {
    //                 setContainerHeight(entry.contentRect.height);
    //             }
    //         });

    //         resizeObserver.observe(node);

    //         // 清理函数
    //         return () => resizeObserver.disconnect();
    //     }
    // }, []);

    const centerStyles = {
        // height: `calc( 100vh - ${topRef.current ? topRef.current?.clientHeight : 0}px)`
    };

    const renderModules = () => {
        if (status === REQ_STATUS.IDLE) {
            if (modules == null) return (<></>);


            return (
                <>
                    <div className={styles.modulePage}>
                        <div className={styles.topArea} ref={topRef} >
                            {/* <p>100</p> */}
                            {/* <div className={styles.header}>
                            Bonus
                        </div> */}
                            {<MobileNav />}
                            {<WithdrawPopup open={showWithdrawPopup} onClose={() => setShowWithdrawPopup(false)} />}

                        </div>

                        <div className={styles.centerArea} style={centerStyles}>
                            <Suspense fallback={<LoadingIn />}>

                                {/* <Spring type={"slideUp"}> */}
                                <div className={`${styles.container} ${isMobile() ? '' : 'page-max-width-wrap'}`} >
                                    {/* <BreadCrumb /> */}
                                    {
                                        modules.map((item, index) => {
                                            // if (index == 1) return (<HomeWithdraw />);
                                            let Comp = AllWidgets[item.type];
                                            // console.error("Comp", item.type);
                                            if (Comp == null) {
                                                console.warn(`Module type "${item.type}" not found in AllWidgets`);
                                                return (<></>);
                                            }
                                            return (
                                                <Fragment key={index}>
                                                    <Comp data={item}></Comp>
                                                </Fragment>
                                            );
                                        })
                                    }
                                </div>
                                {/* </Spring> */}

                            </Suspense>

                            <Footer />
                        </div>
                    </div>
                </>

            );
        }
        else {
            return (<LoadingIn />);
        }
    };
    return (
        <>
            {
                renderModules()
            }
        </>
    );
};
export default ModuleGroup;
