import {useEffect, useState} from "react";
import {useDispatch, useSelector} from "react-redux";
import {getDownloadConf, getPwaCliamStatus, getUserVip} from "@features/mainSlice";
import {formatCash, isFrequentTap} from "@utils/helpers";
import styles from "./styles.module.scss";
import Popup from "@components/Popup";
import img_gift_package from "@assets/pwabonus/gift_package.webp"
import LazyImage from "@components/LazyImage";
import {REQ_STATUS} from "@api/config";
import SmallLoading from "@components/SmallLoading";
import {reqFreeWithdraw, reqGetPwaBonus} from "@features/api";
import { useNavigate } from "react-router-dom";
import { ROUTE_PATH } from "@constants/routes";
import { useWithdrawMission } from "@contexts/withdrawMissionContext";
const i18n = global.i18n;
const WPopPwaBonus = () => {
    const [isShow, setIsShow] = useState(false);
    const downConf=useSelector(getDownloadConf)
    const claimStaus=useSelector(getPwaCliamStatus)
    const dispatch = useDispatch();
    const navigate = useNavigate();
    const { open: missionOpen, setOpen: setMissionOpen } = useWithdrawMission();
    const vip = useSelector(getUserVip);

    const show=()=>{
        setIsShow(true);
    }
    const hide=()=>{
        setIsShow(false);
        global.openNextPopup();
    }
    const getDownBonus=()=>{
        let bonus=Number(downConf?.bonus);
        return global.DOLLAR+formatCash(bonus,0);
    }
    const onClaimCallback=(payload)=>{
        if (payload && payload.code === 200) {
            global.showDropCoins();

            // 领取奖励后展示提现界面或者提现任务
            if (vip > 0) setMissionOpen(true);
            else navigate(ROUTE_PATH.FREEWITHDRAW);
            hide();
        }
    }
    const handleClickClaim=()=>{
        if (claimStaus===REQ_STATUS.LOADING)return;
        if (isFrequentTap("claim_pwa_bons"))return;
        dispatch(reqGetPwaBonus({
            callback:onClaimCallback
        }));
    }
    useEffect(()=>{
        global.popPwaBonus={
            show,
            hide
        };
        return ()=>{

        }
    },[]);
    return (
        <Popup onClose={() => {
            hide();
        }} open={isShow} btnCloseType={0} popupClass={styles.popup}>
            <div className={styles.container}>
                <LazyImage src={img_gift_package} alt={""} className={styles.gift_package}></LazyImage>
                <div className={styles.title}>{i18n.t("popPwaBonus.title")}</div>
                <div className={styles.desc}>
                    {i18n.t("popPwaBonus.desc")}
                    <span>{" "+getDownBonus()}</span>
                </div>
                <button className={styles.action} onClick={handleClickClaim}>
                    {
                        claimStaus===REQ_STATUS.LOADING?(<SmallLoading fill='#fff'/>):(i18n.t("popPwaBonus.claim"))
                    }
                </button>
            </div>
        </Popup>
)
}
export default WPopPwaBonus;
