import React, {useEffect, useRef, useState} from "react";
import styles from "./styles.module.scss";
import Modal from "@mui/material/Modal";
import Fade from "@mui/material/Fade";
import Grow from "@mui/material/Grow";
import { gsap } from 'gsap';
import {useDispatch, useSelector} from "react-redux";
import {
    getCPFFirst,
    getFirstPayMulti,
    getGetSecondStatus,
    getOFirstPay,
    getPaymentOrderStatus
} from "@features/paySlice";
import {ROUTE_PATH} from "@constants/routes";
import {REQ_STATUS} from "@api/config";
import {reqGetSecond, reqPaymentOrder} from "@features/api";
import {useNavigate} from "react-router-dom";
import {getUserInfo, isLogined} from "@features/mainSlice";
import SmallLoading from "@components/SmallLoading";
import {useThemeProvider} from "@contexts/themeContext";
import {APP_COUNTRY_CODE, APP_WELFARE} from "@constants/app";
import BRCPFSave from "@widgets/WDeposit/BR/BRCPFSave/BRCPFSave";
import RUPaytypeSelect from "@widgets/WDeposit/RU/RUPaytypeSelect";
import {formatTime, localStorageGet, localStorageSet, stringFormat} from "@utils/helpers";
import {LOCAL_MULTI_FIRST_GUIDE} from "@constants/localkey";
const i18n=global.i18n;
const objInfo={
    guideTimer:null,
    tl:null
};
const WFirstPay=()=>{
    const [isShow, setIsShow] = useState(false);
    const firstPayConf=useSelector(getOFirstPay);
    const dispatch = useDispatch();
    const navigate=useNavigate();
    const user=useSelector(getUserInfo);
    const orderStatus=useSelector(getPaymentOrderStatus);
    const {setWelfTabState}=useThemeProvider();
    const isLogin=useSelector(isLogined);
    const cpfFirst=useSelector(getCPFFirst);
    const areaItem=global.getLocalAreaItem();
    const firstPayMulti=useSelector(getFirstPayMulti);
    const [selectIndex,setSelectIndex]=useState(0);
    const getSecondStatus=useSelector(getGetSecondStatus);
    const handRef=useRef(null);
    const [showGuide,setShowGuide]=useState(false);
    const show=()=>{
        setIsShow(true);
        setWelfTabState(APP_WELFARE.FIRST_PAY);
    }
    const hide=()=>{
        setIsShow(false);
        setWelfTabState(-1);
    }
    const onClose=()=>{
        hide();
        global.openNextPopup();
    }
    useEffect(()=>{
        const firstPay={
            show,
            hide
        };
        global.firstPay=firstPay;
        return ()=>{
        }
    },[])
    useEffect(()=>{
        if (firstPayMulti){
            setSelectIndex(firstPayMulti.default)
        }
    },[firstPayMulti])
    useEffect(() => {
        clearGuideTimer();
        if (isShow){
           checkShowGuide();
        }
    }, [isShow]);
    const clearGuideTimer=()=>{
        if (objInfo.guideTimer){
            clearTimeout(objInfo.guideTimer);
            objInfo.guideTimer=null;
        }
        if (objInfo.tl){
            objInfo.tl.kill();
            objInfo.tl=null;
        }
    }
    const checkShowGuide=()=>{
        let items=firstPayMulti.items;
        let isguide=items!=null&&items.length>1;
        let lflag=localStorageGet(LOCAL_MULTI_FIRST_GUIDE,"0");
        if (isguide)isguide=lflag==="0";
        setShowGuide(isguide);
        clearGuideTimer();
        if (isguide){
            objInfo.guideTimer=setTimeout(()=>{
                let target=handRef.current;
                if (target){
                    let tl=gsap.timeline();
                    objInfo.tl=tl;
                    tl.fromTo(target,{x:180,y:420,opacity:0},{x:130,y:330,opacity:1}).call(()=>{setSelectIndex(0)});
                    tl.to(target,{x:265,y:330},"+=1").call(()=>{setSelectIndex(1)});
                    tl.to(target,{x:130,y:330},"+=1").call(()=>{setSelectIndex(0)});
                    tl.to(target,{x:265,y:330},"+=1").call(()=>{setSelectIndex(1)});
                    tl.to(target,{x:180,y:420,opacity:0},"+=1").call(()=>{setShowGuide(false)})
                }
            },500)
            localStorageSet(LOCAL_MULTI_FIRST_GUIDE,"1");
        }
    }
    const getPayItem=()=>{
        if (firstPayMulti){
            let items=firstPayMulti.items;
            if (items)return items[selectIndex];
            else return firstPayMulti.leftitem;
        }
        return null;
    }
    const onGetPaymentCallback=()=>{
        hide();
        navigate(ROUTE_PATH.PAY_ORDER);
    }
    const onGetPaymentOder=(data)=>{
        if (!isLogin){
            hide();
            navigate(ROUTE_PATH.SIGN_IN);
            return;
        }
        if (orderStatus===REQ_STATUS.LOADING)return;
        let reqOrder=()=>{
            data.user=user;
            data.callback=onGetPaymentCallback;
            // data.callbackError=callbackErr;
            // dispatch(reqPaymentOrder(data));
            dispatch(reqPaymentOrder(data)).then((odata)=>{
                if (odata.payload){
                    callbackErr(odata.payload);
                }
            });
        }
        let callbackErr=(payload)=>{
            if (payload&&payload.code===301){
                if (areaItem.code===APP_COUNTRY_CODE.EU){
                    if (global.wdepositInfo!=null){
                        global.wdepositInfo.show(()=>{
                            reqOrder();
                        });
                    }
                }
            }
        }
        if (areaItem.code===APP_COUNTRY_CODE.RU){
            if (global.ruPaytypeSelect!=null){
                global.ruPaytypeSelect.show((eventType)=>{
                    data.eventType=eventType;
                    reqOrder();
                });
            }
        }
        else if (areaItem.code===APP_COUNTRY_CODE.BR){
            if (cpfFirst){
                if (global.brCPFSave!=null){
                    global.brCPFSave.show(()=>{
                        data.cpf_first=1;
                        reqOrder();
                    })
                }
            }
            else
            {
                reqOrder();
            }
        }
        else{
            reqOrder();
        }
    }
    const getSecondCallback=(payload)=>{
        if (payload&&payload.code===200){
            hide();
        }
    }
    const onGetSecond=()=>{
        if (getSecondStatus===REQ_STATUS.LOADING)return;
        let data={};
        data.callback=getSecondCallback;
        dispatch(reqGetSecond(data))
    }
    const renderMain=()=>{
        let payItem=getPayItem();
        if (payItem==null)return (<></>);
        let first_pay=payItem;
        let give=0;
        let money=0;
        let total=0;
        let second_give=0;
        let precent="";
        if (first_pay!=null){
            give=Number(first_pay.give);
            money=Number(first_pay.money);
            second_give=Number(first_pay.second_give);
            total=give+money;
            precent=''+Math.floor((give+second_give)*100/money)+'%';
        }
        let isdone=first_pay.timeleft!=null;
        if (second_give>0){
            return (
                <div className={styles.f_main}>
                    <img className={styles.bglight} src={require('@assets/firstPay/bglight.png')}/>
                    <div className={styles.pack_con}>
                        <img className={styles.pack_bg} src={require('@assets/firstPay/pack.png')}/>
                        <div className={`${styles.bonus_con} ${styles.p_left}`}>
                            <img className={styles.l_bg} src={require('@assets/firstPay/l_bg.png')}/>
                            <span data-title={global.DOLLAR + total}
                                  className={styles.p_text}>{global.DOLLAR + total}</span>
                            <span className={styles.p_label}>{i18n.t("firstPay.today")}</span>
                        </div>
                        <div className={`${styles.bonus_con} ${styles.p_right}`}>
                            <img className={styles.r_bg} src={require('@assets/firstPay/r_bg.png')}/>
                            <span data-title={global.DOLLAR + second_give}
                                  className={styles.p_text}>{global.DOLLAR + second_give}</span>
                            <span className={styles.p_label}>{i18n.t("firstPay.day_2")}</span>
                        </div>
                        {/*<div className={styles.percent_con}>*/}
                        {/*<div data-title={precent} className={styles.text}>{precent}</div>*/}
                        {/*</div>*/}
                        <div className={styles.percent_con}>
                            <div data-title={precent + " " + i18n.t("firstPay.up")}
                                 className={styles.p_text}>{precent + " " + i18n.t("firstPay.up")}</div>
                        </div>
                        {
                            isdone ? (
                                <div className={styles.already_con}>
                                    <img className={styles.mask} src={require('@assets/firstPay/mask.png')}/>
                                    <div className={styles.flag_con}>
                                        <img className={styles.flag_bg} src={require('@assets/firstPay/flag.png')}/>
                                        <div className={styles.flag_label}>{i18n.t("firstPay.already_got")}</div>
                                    </div>
                                </div>
                            ) : (<></>)
                        }
                    </div>
                </div>
            )
        }
        else
        {
            return (
                <div className={styles.f_main}>
                    <img className={styles.bglight} src={require('@assets/firstPay/bglight.png')}/>
                    <div className={styles.pack_con}>
                        <img className={styles.pack_bg} src={require('@assets/firstPay/pack.png')}/>
                        <div className={styles.percent_con_old}>
                            <div data-title={'+'+precent} className={styles.text}>{'+'+precent}</div>
                        </div>
                        <div className={styles.percent_con}>
                            <div data-title={global.DOLLAR+total}
                                 className={styles.p_text}>{global.DOLLAR+total}</div>
                        </div>
                    </div>
                </div>
            )
        }
    }
    const renderPayBtn = () => {
        let payItem = getPayItem();
        if (payItem == null) return (<></>);
        let first_pay = payItem;
        let money = 0;
        let payType = 0;
        if (first_pay != null) {
            money = Number(first_pay.money);
            payType = first_pay.id;
            let gear = first_pay.gear;
            if (gear != null) {
                gear = JSON.parse(gear);
                if (gear)gear=gear[0];
                payType=gear.id;
            }
        }
        let status=-1;
        let timeleft=0;
        if (first_pay.timeleft!=null){
            timeleft=Number(first_pay.timeleft);
            status=timeleft<=0?1:0;
        }
        let label=(<></>);
        if (status===-1){
            label=orderStatus===REQ_STATUS.LOADING?(<SmallLoading fill={"#fff"}/>):(
                <>
                            <span data-title={i18n.t("firstPay.only_need")}
                                  className={styles.label}>{i18n.t("firstPay.only_need")}</span>
                    <span data-title={global.DOLLAR + money}
                          className={styles.pay_num}>{global.DOLLAR + money}</span>
                </>
            )
        }
        else if (status===0){
            let left_str=stringFormat(i18n.t("firstPay.time_left"),[formatTime(timeleft)])
            label=(
                <>
                    <span data-title={left_str}
                          className={styles.label_time}>{left_str}</span>
                </>
            )
        }
        else if (status===1){
            label=getSecondStatus===REQ_STATUS.LOADING?(<SmallLoading fill={"#fff"}/>):(
                <>
                    <span data-title={i18n.t("firstPay.label_claim")}
                          className={styles.label}>{i18n.t("firstPay.label_claim")}</span>
                </>
            )
        }
        return (
            <button className={styles.f_btnpay} onClick={() => {
                if (status === -1) {
                    onGetPaymentOder({
                        price:money,
                        goodsName:"firstpay",
                        payType:payType,
                        GiftsID:first_pay.gift_id
                    })
                }
                else if (status===1)
                {
                    onGetSecond();
                }
            }}>
                {/*{*/}
                {/*    orderStatus===REQ_STATUS.LOADING?(<SmallLoading fill={"#fff"}/>):(*/}
                {/*        <>*/}
                {/*            <span data-title={i18n.t("firstPay.only_need")}*/}
                {/*                  className={styles.label}>{i18n.t("firstPay.only_need")}</span>*/}
                {/*            <span data-title={global.DOLLAR + money}*/}
                {/*                  className={styles.pay_num}>{global.DOLLAR + money}</span>*/}
                {/*        </>*/}
                {/*    )*/}
                {/*}*/}
                {label}
            </button>
        )
    }
    const renderPayTabs=()=>{
        let items=[];
        if (firstPayMulti){
            items=firstPayMulti.items;
        }
        if (items==null||items.length<=1)return (<div></div>);
        return (
            <div className={styles.f_ptabs_con}>
                {
                    items.map((item,index)=>{
                        let t_img=index===selectIndex?1:0;
                        return (
                            <button className={styles.tab_con} key={index} onClick={()=>{
                                setSelectIndex(index);
                            }}>
                                <img className={styles.t_bg} src={require(`@assets/firstPay/tab_${t_img}.png`)}/>
                                <div className={styles.t_label_con}>
                                    <span data-title={global.DOLLAR + item.money} className={styles.t_text}>{global.DOLLAR+item.money}</span>
                                </div>
                            </button>
                        )
                    })
                }
            </div>
        )
    }
    const renderTabsGuide=()=>{
        if (!showGuide)return (<></>);
        return (
            <div className={styles.f_tab_guide}>
                <img ref={handRef} className={styles.f_hand} src={require('@assets/firstPay/guide.png')}/>
            </div>
        )
    }
    const renderPaytypeSelect=()=>{
        if (areaItem.code===APP_COUNTRY_CODE.RU){
            return (<RUPaytypeSelect/>)
        }
        else
        {
            return (<></>);
        }
    }
    const renderCPFSave=()=>{
        if (areaItem.code===APP_COUNTRY_CODE.BR){
            return (<BRCPFSave/>)
        }
        else
        {
            return (<></>)
        }
    }
    return (
        <>
            <Modal open={isShow} onClose={onClose} closeAfterTransition>
                <Fade in={isShow} timeout={500}>
                    <div className={styles.container}>
                        <Grow in={isShow} timeout={500}>
                            <div className={styles.f_con}>
                                <img className={styles.title} src={require(`@assets/firstPay/${i18n.language}.png`)}/>
                                {renderMain()}
                                {renderPayTabs()}
                                {renderPayBtn()}
                                {renderTabsGuide()}
                            </div>
                        </Grow>
                    </div>
                </Fade>
            </Modal>
            {renderPaytypeSelect()}
            {renderCPFSave()}
        </>
    )
}
export default WFirstPay;
