import styles from "./styles.module.scss";
import WWheel from "@widgets/WCashWheel/WWheel/WWheel";
import Spring from "@components/Spring";
import cash_2 from "@assets/wheel/cash_2.png";
// import coin from "@assets/wheel/pix_2.png";
import { useDispatch, useSelector } from "react-redux";
import { getBonusStatus, getMyRecord, getRecord, getTurnplate } from "@features/turnplateSlice";
import { formatCash, stringFormat } from "@utils/helpers";
import React, { useEffect, useState, useRef } from "react";
import { Autoplay, EffectCube, EffectCoverflow, Virtual } from "swiper/modules";
import { Swiper, SwiperSlide } from "swiper/react";
import styled from 'styled-components/macro';
import CountUp from "react-countup";
import Popup from "@components/Popup";
import WShare from "@widgets/WCashWheel/WShare/WShare";
import { isLogined } from "@features/mainSlice";
import { useNavigate } from "react-router";
import { ROUTE_PATH } from "@constants/routes";
import SmallLoading from "@components/SmallLoading";
import WRetainPop from "@widgets/WCashWheel/WRetainPop/WRetainPop";
import WInviteRecordPop from "@widgets/WCashWheel/WInviteRecord/WInviteRecordPop";
import { reqTurnplateBonus } from "@features/api";
import { REQ_STATUS } from "@api/config";
import { useThemeProvider } from "@contexts/themeContext";
import bg from "@assets/wheel/bg.png";
import cashBox from "@assets/wheel/cashBox.png";
import popup from "@assets/wheel/popup.png";
import btn1 from "@assets/wheel/btn1.png";
import btn2 from "@assets/wheel/btn2.png";
import shareIcon from "@assets/wheel/share.png";
import coin from "@assets/wheel/coin.png";
import { toast } from "react-toastify";
import WITHDRAW_TYPE from "@constants/withdraw_types";

const i18n = global.i18n;
const StyledSwiper = styled(Swiper)`
    height: 100%; /* 必须设置高度 */
    .swiper-wrapper {
        transition-timing-function: linear;
    }
`;
const WCashWheel = ({ close }) => {
    const turnplate = useSelector(getTurnplate);
    // if(turnplate==null)turnplate={collect_amount:0,total_amount:10000};
    const record = useSelector(getRecord);
    const myrecord = useSelector(getMyRecord);
    const [recordIndex, setRecordIndex] = useState(0);
    const recordLog = [record, myrecord];
    const [swiper, setSwiper] = useState(null);
    const [openInfoBox, setOpenInfoBox] = useState(false);
    const [openShare, setOpenShare] = useState(false);
    const [openInviteRecord, setOpenInviteRecord] = useState(false);
    const isLogin = useSelector(isLogined);
    const navigate = useNavigate();
    const dispatch = useDispatch();
    const bonusStatus = useSelector(getBonusStatus);

    const { setIsShowWheel } = useThemeProvider();

    useEffect(() => {
        if (turnplate == null || turnplate.times > 0) {
            setIsShowWheel(true);
        }

        // 可选的清理函数
        return () => {
            setIsShowWheel(false); // 组件卸载时重置状态
        };
    }, [turnplate, setIsShowWheel]); // 添加依赖项


    useEffect(() => {
        if (swiper) {
            swiper.update();
        }
        return () => {
        };
    }, [swiper]);
    useEffect(() => {

    }, [recordIndex]);
    const formatPhone = (phone) => {
        let tstr = phone.substring(1, phone.length - 2);
        phone = phone.replace(tstr, '*'.repeat(tstr.length));
        if (!phone.startsWith("55")) phone = "55" + phone;
        return phone;
    };
    const checkClickWD = () => {
        let collect = turnplate.collect_amount;
        let total = turnplate.total_amount;
        if (collect >= total) {
            if (bonusStatus !== REQ_STATUS.LOADING) {
                dispatch(reqTurnplateBonus());
            }
        }
        else {
            setOpenInfoBox(true);
        }
    };
    const renderCashMain = () => {
        let collect = turnplate.collect_amount;
        // collect=10000;
        let total = turnplate.total_amount;
        let left = total - collect;
        let isEnableCash = collect > 0;
        let progress = ((collect / total) * 100).toFixed(2);
        return (
            <div className={styles.cash_main_con}>
                <div className={styles.cash_main}>
                    <div className={styles.have_cash}>
                        <img className={styles.cash_img} src={cash_2} />
                        <CountUp
                            start={0}
                            end={Number(formatCash(collect))}
                            duration={1}
                            separator=" "
                            decimals={2}
                            prefix={global.DOLLAR + " "}
                            startOnMount
                        >
                            {({ countUpRef, start }) => {
                                if (countUpRef.current) {
                                    let current = countUpRef.current;
                                    if (current.value !== collect) {
                                        start();
                                        current.value = collect;
                                    }
                                }
                                return (
                                    <div ref={countUpRef} className={styles.cash_text} />
                                );
                            }}
                        </CountUp>
                        {/*<div className={styles.cash_text}>{global.DOLLAR+" "+formatCash(collect)}</div>*/}
                        <button className={styles.cash_btn} disabled={!isEnableCash} onClick={() => {
                            // setOpenInfoBox(true);
                            checkClickWD();
                        }}>
                            {
                                bonusStatus === REQ_STATUS.LOADING ? (<SmallLoading fill={"#fff"} />) : (
                                    <>
                                        <img className={styles.icon} src={coin} />
                                        {i18n.t("turnplate.cash_btn")}
                                    </>
                                )
                            }
                        </button>
                    </div>
                    <div className={styles.progress}>
                        <div>{progress + "%"}</div>
                        <div className={styles.bar}>
                            <span className={styles.dot} style={{ width: progress + "%" }}>
                                <div className={styles.custor}></div>
                            </span>
                        </div>
                    </div>
                    <div className={styles.need_cash}>
                        <div>{i18n.t("turnplate.need_tip")}</div>
                        <div className={styles.need_txt}>{formatCash(left)}</div>
                        <div>{i18n.t("turnplate.need_tip_1")}</div>
                    </div>
                </div>
            </div>
        );
    };
    // const renderRecord = () => {
    //     let list = recordLog[recordIndex];
    //     return (
    //         <div className={styles.record_con}>
    //             <div className={styles.record}>
    //                 <div className={styles.record_tab}>
    //                     <button disabled={recordIndex === 0} onClick={() => {
    //                         setRecordIndex(0);
    //                     }}>
    //                         {i18n.t("turnplate.record.tab_0")}
    //                     </button>
    //                     <button disabled={recordIndex === 1} onClick={() => {
    //                         setRecordIndex(1);
    //                     }}>
    //                         {i18n.t("turnplate.record.tab_1")}
    //                     </button>
    //                 </div>
    //                 {
    //                     list == null || list.length === 0 ? (<></>) : (
    //                         <StyledSwiper
    //                             className={styles.swiper_list}
    //                             onSwiper={setSwiper}
    //                             direction={"vertical"}
    //                             spaceBetween={0}
    //                             slidesPerView={6}
    //                             loop={true}
    //                             autoplay={{ delay: 0, disableOnInteraction: false }}
    //                             effect="fade"
    //                             fadeEffect={{ crossFade: true }}
    //                             modules={[Autoplay, Virtual]}
    //                             speed={800}
    //                             virtual={true}
    //                         >
    //                             {
    //                                 list.map((item, index) => {
    //                                     let phone = formatPhone(item.phone);
    //                                     let name = item.name;
    //                                     let amount = item.amount;
    //                                     return (
    //                                         <SwiperSlide key={index} virtualIndex={index}>
    //                                             <div className={styles.swiper_item}>
    //                                                 <div>{phone}</div>
    //                                                 <div className={styles.name}>{name}</div>
    //                                                 <div className={styles.coins_con}>
    //                                                     {"+" + amount}
    //                                                     <div className={styles.unit}>{global.DOLLAR}</div>
    //                                                 </div>
    //                                             </div>
    //                                         </SwiperSlide>
    //                                     );
    //                                 })
    //                             }
    //                         </StyledSwiper>
    //                     )
    //                 }
    //             </div>
    //         </div>
    //     );
    // };
    const renderHelp = () => {
        let arr = Array.from({ length: 6 }, (_, index) => index + 1);
        return (
            <div className={styles.rule_con}>
                <div className={styles.rule}>
                    <div className={styles.title}>{i18n.t("turnplate.rule.title")}</div>
                    {
                        arr.map((item, index) => {
                            return (
                                <div key={index}>{i18n.t("turnplate.rule.rule_" + item)}</div>
                            );
                        })
                    }
                </div>
            </div>
        );
    };
    const renderInfoBox = () => {
        let collect = turnplate.collect_amount;
        // collect=9556;
        let total = turnplate.total_amount;
        let left = total - collect;
        return (
            <Popup open={openInfoBox} onClose={() => {
                setOpenInfoBox(false);
            }}>
                <div className={styles.info_box}>
                    <div className={styles.title}>{i18n.t("turnplate.info_box.title")}</div>
                    <div className={styles.content}>
                        <div className={styles.cash_con}>
                            <div className={styles.tips}>
                                {i18n.t("turnplate.info_box.tips")}
                            </div>
                            <CountUp
                                start={openInfoBox ? 0 : Number(formatCash(collect))}
                                end={Number(formatCash(collect))}
                                duration={1}
                                separator=" "
                                decimals={2}
                                suffix={` ${global.currency}`}

                            >
                                {({ countUpRef, start }) => {
                                    return (
                                        <div ref={(ref) => {
                                            countUpRef.current = ref;
                                            if (openInfoBox) start();
                                        }} className={styles.cash} />
                                    );
                                }}
                            </CountUp>
                        </div>
                        <div className={styles.step_con}>
                            <div>{i18n.t("turnplate.info_box.step_title")}</div>
                            <div className={styles.step_content}>
                                <div className={`${styles.step_item} ${collect > 0 ? styles.active : ''}`}>{i18n.t("turnplate.info_box.step_0")}</div>
                                <div className={`${styles.step_item} ${collect > 0 ? styles.active : ''}`}>{stringFormat(i18n.t("turnplate.info_box.step_1"), [formatCash(left)])}</div>
                                <div className={`${styles.step_item} ${collect >= total ? styles.active : ''}`}>{stringFormat(i18n.t("turnplate.info_box.step_2"), [formatCash(total, 0)])}</div>
                            </div>
                        </div>
                        <button className={styles.invite_btn} onClick={() => {
                            setOpenInfoBox(false);
                            checkOpenShare();
                        }}>
                            {i18n.t("turnplate.info_box.btn_invite")}
                        </button>
                    </div>
                </div>
            </Popup>
        );
    };

    const renderShare = () => {
        return (
            <WShare open={openShare} onClose={() => {
                setOpenShare(false);
            }}></WShare>
        );
    };
    const renderInviteRecord = () => {
        return (
            <WInviteRecordPop open={openInviteRecord} onClose={() => {
                setOpenInviteRecord(false);
            }}></WInviteRecordPop>
        );
    };

    const checkOpenShare = () => {
        if (!isLogin) {
            navigate(ROUTE_PATH.SIGN_IN);
            return;
        }
        setOpenShare(true);
    };

    const displayRecords = record.slice(0, 10);

    const renderRecord = () => {

        return (
            <div className={styles.marquee_con}>
                <StyledSwiper
                    direction={"vertical"}
                    slidesPerView={1}
                    loop={true}
                    autoplay={{
                        delay: 2500,
                        disableOnInteraction: false,
                        pauseOnMouseEnter: true, // 鼠标悬停暂停
                        waitForTransition: false // 不等待过渡完成
                    }}
                    modules={[Autoplay]}
                    speed={600}
                    simulateTouch={false} // 禁用触摸
                    allowTouchMove={false} // 禁用触摸移动
                >
                    {displayRecords.map((item, index) => (
                        <SwiperSlide key={index}>
                            <div className={styles.marquee_item}>
                                <span className={styles.avatar} />
                                <span className={styles.phone}>
                                    {formatPhone(item.phone)}
                                </span>
                                <span className={styles.tip} >
                                    Just withdraw
                                </span>
                            </div>
                        </SwiperSlide>
                    ))}
                </StyledSwiper>
            </div>
        );
    };




    const renderMain = () => {
        let collect = turnplate.collect_amount;
        // collect=10000;
        let total = turnplate.total_amount;
        let left = total - collect;

        let canWithdraw = collect >= total;
        const handleClickWithdraw = () => {
            if (canWithdraw) {
                // global.fixedScore = { score: collect };
                // navigate(ROUTE_PATH.REFERRAL);
                global.openFixedWithdraw && global.openFixedWithdraw({
                    type: WITHDRAW_TYPE.SHARE,
                });
            } else {
                toast.info(`Invite friends to earn rewards. Once you reach $${total / 100}, you can withdraw`,{toastId:"withdraw_tip"});
            }
        };
        return (
            <>
                <div className={styles.topArea}>
                    <img src={bg} alt="" className={styles.bg} />

                    <div className={styles.cashArea}>
                        <img src={cashBox} alt="" className={styles.cashBox} />
                        {/* <span>${Number(formatCash(collect))}</span> */}

                        <CountUp
                            start={0}
                            end={Number(formatCash(collect))}
                            duration={1}
                            separator=""
                            decimals={2}
                            prefix={global.DOLLAR + ""}
                            startOnMount
                        >
                            {({ countUpRef, start }) => {
                                if (countUpRef.current) {
                                    let current = countUpRef.current;
                                    if (current.value !== collect) {
                                        start();
                                        current.value = collect;
                                    }
                                } else {
                                    setTimeout(() => {
                                        start();
                                    }, 200);
                                    // return (<span>${Number(formatCash(collect))}</span>);
                                }

                                return (
                                    // <div ref={countUpRef} className={styles.cash_text} />
                                    <span ref={countUpRef} />
                                );
                            }}
                        </CountUp>
                    </div>

                </div>
                <div className={styles.btnArea}>
                    <div className={styles.remainTip}>
                        <img src={popup} alt="" />

                        <div className={styles.need_cash}>
                            {
                                canWithdraw ? (
                                    <>
                                        Withdraw <div className={styles.need_txt}>${formatCash(collect)}</div> now.
                                    </>
                                ) : (
                                    <>
                                        <div>{i18n.t("turnplate.need_tip")}</div>
                                        <div className={styles.need_txt}>${formatCash(left)}</div>
                                        <div>{i18n.t("turnplate.need_tip_1")}</div>
                                        <div className={styles.need_txt}>${total / 100}</div>
                                    </>
                                )
                            }
                        </div>
                    </div>
                    <div className={styles.btns}>
                        <div className={`${styles.withdrawBtn} ${canWithdraw ? styles.enableBtn : ""}`} onClick={handleClickWithdraw}>
                            <img src={canWithdraw ? btn2 : btn1} alt="" />
                            <span>Withdraw</span>
                        </div>
                        <div className={`${styles.recordBtn} ${styles.enableBtn}`} onClick={() => setOpenInviteRecord(true)}>
                            <img src={btn2} alt="" />
                            <span>Invited Users</span>
                        </div>
                    </div>
                </div>

                <div className={styles.shareBtn} onClick={checkOpenShare}>
                    <img src={shareIcon} alt="" />
                    <div className={styles.text}>
                        <span className={styles.line1}>Share with friends</span>
                        <span className={styles.line2}>Earn $0.01 - 5 bonus</span>
                    </div>
                </div>
            </>
        );
    };

    const renderTips = () => {
        return (
            <div className={styles.tips}>
                <div className={styles.item}>
                    <img src={coin} alt="" />
                    <span>Withdraw once you reach $40</span>
                </div>
                <div className={styles.item}>
                    <img src={coin} alt="" />
                    <span>Earn $0.1-5 when your friends deposit</span>
                </div>
                <div className={styles.item}>
                    <img src={coin} alt="" />
                    <span>Earn $0.01-0.5 when your friends register and play</span>
                </div>
                <div className={styles.item}>
                    <img src={coin} alt="" />
                    <span>Receive a 1% bonus on each deposit made by your friends</span>
                </div>
            </div>
        );
    };
    const renderPDD = () => {
        return (
            <Spring type={"slideUp"} className={styles.content}>
                {
                    renderMain()
                }
                {
                    renderRecord()
                }
                {
                    renderTips()
                }


                {/* other */}
                {
                    renderShare()
                }
                {
                    renderInviteRecord()
                }

            </Spring>
        );
    };
    return (
        <div className={styles.container}>
            {
                turnplate == null ? (<SmallLoading></SmallLoading>) : (renderPDD())
            }
        </div>
    );
};
export default WCashWheel;
