import styles from './styles.module.scss';
import { useDispatch, useSelector } from "react-redux";
import { getUserInfo, isLogined } from "@features/mainSlice";
import {
    getConfig,
    getCPFFirst,
    getFirstPay,
    getFirstPayMulti, getGetSecondStatus,
    getPaymentOrderStatus,
    getShowBonus
} from "@features/paySlice";
import fpayimg from "@assets/pay/fpayimg.png";
import img_sc from "@assets/pay/img_sc_66.png";
import React, { useState } from "react";
import Spring from "@components/Spring";
import { REQ_STATUS } from "@api/config";
import SmallLoading from "@components/SmallLoading";
import { reqGetSecond, reqPaymentOrder } from "@features/api";
import { useNavigate } from "react-router-dom";
import { ROUTE_PATH } from "@constants/routes";
import RadioBtn from "@components/RadioBtn";
import img_bonus from "@assets/pay/topup_bonus.png";
import styled from 'styled-components/macro';
import { formatCurrency, formatTime, stringFormat } from "@utils/helpers";
import { APP_COUNTRY_CODE } from "@constants/app";
import RUPaytypeSelect from "@widgets/WDeposit/RU/RUPaytypeSelect";
import BRCPFSave from "@widgets/WDeposit/BR/BRCPFSave/BRCPFSave";
import { Swiper, SwiperSlide } from "swiper/react";
import { Autoplay } from "swiper/modules";
import usePaymentActions from '@hooks/usePaymentActions';
const i18n = global.i18n;
const PPBanner = styled.div`
    background: url(${img_bonus});
    background-size: 100% 100%;
`
const StyledSwiper = styled(Swiper)`
    width: 100%;
 padding: 0px 0px;
 .swiper-wrapper{
    transition-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1.275);
 }
 .swiper-slide{
    width: 100%;
 }
`
const BRDeposit = () => {
    const dispatch = useDispatch();
    const navigate = useNavigate();
    const user = useSelector(getUserInfo);
    const firstpay = useSelector(getFirstPay);
    const config = useSelector(getConfig);
    const orderStatus = useSelector(getPaymentOrderStatus);
    const [selectedID, setSelectedID] = useState("0");
    const isLogin = useSelector(isLogined);
    const [selectedPromotion, setSelectedPromotion] = useState(false);
    const showBonus = useSelector(getShowBonus);
    const cpfFirst = useSelector(getCPFFirst);
    const areaItem = global.getLocalAreaItem();
    const [swiper, setSwiper] = useState(null);
    const firstPayMulti = useSelector(getFirstPayMulti);
    const getSecondStatus = useSelector(getGetSecondStatus);

    const { startPayingOrder } = usePaymentActions();

    const getSelectedConfig = () => {
        let selected = null;
        if (config) {
            for (let i = 0; i < config.length; i++) {
                let item = config[i];
                if (item.id === selectedID) {
                    selected = item;
                    break;
                }
            }
        }
        return selected;
    }
    const onGetPaymentCallback = () => {
        navigate(ROUTE_PATH.PAY_ORDER);
    }
    const onGetPaymentOder = (data) => {
        if (!isLogin) {
            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)).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 getGiftImg = () => {
        try {
            let DOLLAR = global.DOLLAR;
            let icon = require(`@assets/pay/fpayimg_${DOLLAR}.png`);
            return icon;
        }
        catch (err) {
            return require(`@assets/pay/fpayimg_$.png`);
        }
    }
    const getMultiInfo = () => {
        let items = [];
        let status = -1;
        if (firstPayMulti != null) {
            if (firstPayMulti.items != null) {
                // items=firstPayMulti.items;
                let fitems = firstPayMulti.items;
                for (let i = 0; i < fitems.length; i++) {
                    if (i === firstPayMulti.default) items.unshift(fitems[i]);
                    else items.push(fitems[i]);
                }
            }
            else {
                let leftitem = firstPayMulti.leftitem;
                if (leftitem != null) {
                    items.push(leftitem);
                    let timeleft = leftitem.timeleft;
                    status = timeleft <= 0 ? 1 : 0
                }
            }
        }
        return { status, items };
    }
    const getSecondCallback = (payload) => {
        if (payload && payload.code === 200) {

        }
    }
    const onGetSecond = () => {
        if (getSecondStatus === REQ_STATUS.LOADING) return;
        let data = {};
        data.callback = getSecondCallback;
        dispatch(reqGetSecond(data))
    }
    const renderFirst = (item, status) => {
        // if (firstpay==null)return (<></>);
        if (item == null) return (<></>);
        let price = Number(item.money);
        let give = Number(item.give);
        let second_give = Number(item.second_give);
        let total = price + give;
        // let title=firstpay.goodsName==="firstpay"?i18n.t("deposit.banner.first_title"):i18n.t("deposit.banner.recommend_title");
        let title = i18n.t("deposit.banner.first_title");
        let btnlabel = (<></>);
        if (status === -1) { btnlabel = (<>{global.DOLLAR + price}</>) }
        else if (status === 0) {
            let left_str = formatTime(item.timeleft)
            btnlabel = (<>{left_str}</>)
        }
        else if (status === 1) {
            btnlabel = getSecondStatus === REQ_STATUS.LOADING ? (<SmallLoading fill={"#fff"} />) : (<>{i18n.t("firstPay.label_claim")}</>)
        }
        return (
            <button className={styles.first_pay} onClick={() => {
                // if (status===-1){
                //     onGetPaymentOder({
                //         price: item.money,
                //         goodsName: "firstpay",
                //         payType: item.id,
                //         GiftsID: item.gift_id
                //     })
                // }
                // else if (status===1){
                //     onGetSecond();
                // }
                global.showFirstPay();
            }}>
                <div className={styles.pay_info}>
                    <div className={styles.title}>{title}</div>
                    <div className={`${styles.price_con} ${second_give <= 0 ? styles.price_con_offset : ''}`}>
                        {
                            status === -1 ? (
                                <>
                                    {
                                        second_give > 0 ? (
                                            <span className={styles.label}>{i18n.t("firstPay.today")}</span>) : (<></>)
                                    }
                                    <span data-title={global.DOLLAR + total}
                                        className={styles.p_text_f}>
                                        {global.DOLLAR + total}
                                    </span>
                                </>
                            ) : (
                                <>
                                    {
                                        second_give > 0 ? (
                                            <span className={styles.label}>{i18n.t("firstPay.today")}</span>) : (<></>)
                                    }
                                    <span data-title={global.DOLLAR + total}
                                        className={styles.p_text_al}>
                                        {global.DOLLAR + total}
                                        <div className={styles.al_line}></div>
                                    </span>
                                </>
                            )
                        }
                        {/*<div className={styles.origin}>*/}
                        {/*    {global.DOLLAR + price}*/}
                        {/*    <div className={styles.ori_line}/>*/}
                        {/*</div>*/}
                    </div>
                    {
                        second_give > 0 ? (
                            <div className={styles.price_con}>
                                <span className={styles.label}>{i18n.t("firstPay.day_2")}</span>
                                <span data-title={global.DOLLAR + second_give}
                                    className={styles.p_text}>{global.DOLLAR + second_give}</span>
                                {/*<div className={styles.origin}>*/}
                                {/*    {global.DOLLAR + price}*/}
                                {/*    <div className={styles.ori_line}/>*/}
                                {/*</div>*/}
                            </div>
                        ) : (<></>)
                    }
                    <button className={styles.price_btn}>
                        {/*{global.DOLLAR + price}*/}
                        {btnlabel}
                    </button>
                </div>
                {/*<img className={styles.gift_img} src={fpayimg}/>*/}
                <img className={styles.gift_img} src={getGiftImg()} />
                <div className={styles.percent}>
                    <img src={img_sc} className={styles.percent} />
                    <div className={styles.text}>
                        {'+' + Math.floor((give + second_give) * 100 / price) + '%'}
                    </div>
                </div>
            </button>
        )
    }
    const renderMultiFirst = () => {
        if (firstPayMulti === null) return (<></>);
        let { status, items } = getMultiInfo();
        return (
            <StyledSwiper onSwiper={setSwiper}
                slidesPerView={1}
                spaceBetween={15}
                loop
                autoplay={{ delay: 5000, disableOnInteraction: false }}
                effect="fade"
                fadeEffect={{ crossFade: true }}
                modules={[Autoplay]}
                speed={1000}
            >
                {
                    items.map((item, index) => {
                        return (
                            <SwiperSlide key={index}>
                                {renderFirst(item, status)}
                            </SwiperSlide>
                        )
                    })
                }
            </StyledSwiper>
        )
    }
    const renderTitle = () => {
        return (
            <div className={styles.title}>{i18n.t("deposit.list.title")}</div>
        )
    }
    const renderBar = () => {
        let item = getSelectedConfig();
        let price = 0;
        let give = 0;
        if (item) {
            price = Number(item.money);
            give = Number(item.give);
            if (selectedPromotion) {
                let activity = item.activity;
                if (activity) {
                    price = Number(activity.money);
                    give = Number(activity.give);
                }
            }
        }
        let total = price + give;
        return (
            <div className={styles.total_bar}>
                <div className={styles.left}>
                    <div className={styles.label}>{global.DOLLAR}</div>
                    <div>{total}</div>
                </div>
                <div className={styles.right}>
                    <div className={styles.extra}>{i18n.t("deposit.list.extra")}</div>
                    <div>{"+" + give}</div>
                </div>
            </div>
        )
    }
    const renderList = () => {
        let list = config;
        if (list == null) list = [];
        let selected = getSelectedConfig();
        let selectedID = "";
        if (selected) selectedID = selected.id;
        return (
            <div className={styles.list}>
                {
                    list.map((item, index) => {
                        let price = Number(item.money);
                        let give = Number(item.give);
                        if (selectedPromotion) {
                            let activity = item.activity;
                            if (activity) {
                                price = Number(activity.money);
                                give = Number(activity.give);
                            }
                        }
                        let extra = "+" + Math.floor(give * 100 / price) + '%';
                        return (
                            <button key={index}
                                className={`${styles.list_btn} ${selectedID === item.id ? styles.active : ''}`}
                                onClick={() => {
                                    setSelectedID(item.id);
                                }}
                            >
                                <div>{global.DOLLAR}</div>
                                {/*<div>{item.money}</div>*/}
                                <div>{formatCurrency(item.money, i18n.getCurrLangKey())}</div>
                                {
                                    give > 0 ? (
                                        <div className={styles.flag}>
                                            <div className={styles.text}>
                                                {extra}
                                            </div>
                                        </div>
                                    ) : (<></>)
                                }

                            </button>
                        )
                    })
                }
            </div>
        )
    }
    const renderDeposits = () => {
        return (
            <div className={styles.list_con}>
                {renderTitle()}
                {renderBar()}
                {renderList()}
            </div>
        )
    }
    const checkOrdinary = (price, goodsName, payType, GiftsID, gear) => {
        let isInFirst = false;
        if (firstPayMulti !== null) {
            let items = firstPayMulti.items;
            if (items != null) {
                for (let i = 0; i < items.length; i++) {
                    let item = items[i];
                    let fmoney = Number(item.money);
                    price = Number(price);
                    if (fmoney === price) {
                        isInFirst = true;
                        break;
                    }
                }
            }
        }
        if (isInFirst) {
            let isPopFirst = false;
            let priceInFirst = global.priceInFirst;
            if (priceInFirst == null) priceInFirst = {};
            if (priceInFirst[price] == null) {
                priceInFirst[price] = 1;
                global.priceInFirst = priceInFirst;
                isPopFirst = true;
            }
            if (isPopFirst) {
                global.showFirstPay();
                return;
            }
        }
        startPayingOrder({
            price: price,
            goodsName: goodsName,
            payType: payType,
            GiftsID: GiftsID,
            gear: gear,
        })
    }
    const renderDepositBtn = () => {
        return (
            <button className={"button-green"} onClick={() => {
                let payItem = getSelectedConfig();
                if (payItem == null) return;
                // let gear = {};
                // if (payItem.gear != null) {
                //     gear = JSON.parse(payItem.gear);
                //     gear = gear[0];
                // }
                // let money = payItem.money;
                // let id = gear.id;
                let gift_id = payItem.gift_id;
                let money = payItem.money;
                if (selectedPromotion) {
                    let activity = payItem.activity;
                    if (activity != null) {
                        money = activity.money;
                        // id=activity.id;
                        gift_id = activity.gift_id;
                    }
                }
                // onGetPaymentOder({
                //     price:money,
                //     goodsName:"chip",
                //     payType:id,
                //     GiftsID:gift_id
                // })
                checkOrdinary(money, "chip", 0, gift_id, payItem.gear);
            }}>
                {orderStatus === REQ_STATUS.LOADING ? (<SmallLoading fill={"#fff"} />) : i18n.t("deposit.pay_btn")}
            </button>
        )
    }
    const renderPromotions = () => {
        if (!showBonus) return (<></>);
        let payItem = getSelectedConfig();
        let percent = 0;
        let bonus = 0;
        if (payItem) {
            let activity = payItem.activity;
            if (activity) {
                let price = Number(activity.money);
                bonus = Number(activity.give);
                percent = Math.floor(bonus * 100 / price);
            }
        }
        return (
            <div className={styles.promotion}>
                {
                    selectedPromotion ? (
                        <PPBanner className={styles.banner}>
                            <div className={styles.info_con}>
                                <div className={styles.percent_tips}>{stringFormat(i18n.t("deposit.promotions.banner_tips"), [percent + "%"])}</div>
                                <div className={styles.big_percent}>{percent + "%"}</div>
                            </div>
                            <div className={styles.info_bonus}>
                                <div>{i18n.t("deposit.promotions.bonus_title")}</div>
                                <div className={styles.bonus_value_con}>
                                    <div>{percent + "%"}</div>
                                    <div className={styles.bonus_value}>{global.DOLLAR + " +" + bonus}</div>
                                </div>
                            </div>
                        </PPBanner>
                    ) : (<></>)
                }
                <div className={styles.select_item}>
                    <RadioBtn className={styles.text} selected={selectedPromotion} value={"promotion"} onChange={(value) => {
                        setSelectedPromotion(!selectedPromotion);
                    }}>
                        {i18n.t("deposit.promotions.tips")}
                    </RadioBtn>
                </div>
            </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 (
        <Spring type="slideUp" className={styles.container}>
            {/*{renderFirst()}*/}
            {renderMultiFirst()}
            {renderDeposits()}
            {renderPromotions()}
            {renderDepositBtn()}
            {renderPaytypeSelect()}
            {renderCPFSave()}
        </Spring>
    )
}
export default BRDeposit;
