import { REQ_STATUS } from "@api/config";
import { APP_COUNTRY_CODE } from "@constants/app";
import { ROUTE_PATH } from "@constants/routes";
import { reqFirstPayGift, reqPaymentOrder } from "@features/api";
import { getUserInfo, isLogined } from "@features/mainSlice";
import { getCPFFirst, getFirstPayGift, getPaymentOrderStatus } from "@features/paySlice";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router";

import icon_cashapp from "@assets/pay/icon_cashapp.webp";
import icon_applePay from "@assets/pay/icon_apple.webp";
import icon_googlePay from "@assets/pay/icon_google.webp";
import icon_paypal from "@assets/pay/icon_paypal.webp";
import { useEffect, useRef } from "react";

const PayTypeMap = {
    "1": "cashapp",
    "2": "paypal",
    "4": "applepay",
    "8": "googlepay",
}

const WithdrawTypeMap = {
    "1": "cashapp",
    "2": "paypal",
}

const SDKConfig = {
    "cashapp": { name: "Cash App", icon: icon_cashapp },
    "paypal": { name: "PayPal", icon: icon_paypal },
    "applepay": { name: "Apple Pay", icon: icon_applePay },
    "googlepay": { name: "Google App", icon: icon_googlePay },
}

const usePaymentActions = () => {
    const navigate = useNavigate();
    const dispatch = useDispatch();
    const isLogin = useSelector(isLogined);
    const orderStatus = useSelector(getPaymentOrderStatus);
    const cpfFirst = useSelector(getCPFFirst);
    const areaItem = global.getLocalAreaItem();
    const user = useSelector(getUserInfo);
    const firstPayGift = useSelector(getFirstPayGift);


    const firstPayGiftRef = useRef(firstPayGift);
    useEffect(() => {
        firstPayGiftRef.current = firstPayGift;
    }, [firstPayGift])


    const onGetPaymentCallback = (data) => {
        navigate(ROUTE_PATH.PAY_ORDER);
    }

    const getPaymentOrder = (data = { price: 0, goodsName: "", payType: "", GiftsID: 0, pay_method: 0, onCompleted: null }) => {
        if (orderStatus === REQ_STATUS.LOADING) return;

        data.payType = 28;
        data.pay_method = data.pay_method;
        const onCompleted = data.onCompleted;
        delete data.onCompleted;
        let reqOrder = () => {
            data.user = user;
            //data.callback = onGetPaymentCallback;
            // data.callbackError=callbackErr;
            dispatch(reqPaymentOrder(data)).then((odata) => {
                if (odata.payload) {
                    callbackErr(odata.payload);
                    //navigate(ROUTE_PATH.PAY_ORDER);
                    onCompleted && onCompleted(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 startPayingOrder = (data = { price: 0, goodsName: "", payType: "", GiftsID: 0, gear: "" }) => {
        if (!isLogin) {
            navigate(ROUTE_PATH.SIGN_IN);
            return;
        }

        global.curGoods = data;
        navigate(ROUTE_PATH.PAYMENTMETHODS);
    }

    const getPaymentConfig = (name) => {
        if (!isNaN(name)) {
            name = PayTypeMap[name] || "cashapp"
        } else {
            name = name || global.curGoods.pay_name;
        }
        return SDKConfig[name];
    }

    const getWithdrawConfig = (type) => {
        const key = WithdrawTypeMap[type] || "cashapp";
        return SDKConfig[key];
    }

    const getFirstPayGiftInfo = () => {
        let info = {
            total_bonus: 0,
            time_left: 0,
            gift_id: 0,
            gift_name: "",
            list: [],
            has_purchased: false,
            bonus_instantly: 0,
            pay_amount: 0,
            day_rewards: {},
            betting_bonus: {},
            betting_task: {},
            expired: 0,
            has_bonus: false,
        };


        // const firstPayGift = firstPayGiftRef.current;
        let firstPayGift = firstPayGiftRef.current;
        if (firstPayGift != null) {
            if (!isNaN(firstPayGift.time_end)) {
                info.time_left = Math.floor((firstPayGift.time_end - Date.now()) / 1000);
            }
            info.list = firstPayGift.list;
            info.has_purchased = firstPayGift.has_purchased;

            if (firstPayGift.gift_info != null) {
                info.total_bonus = firstPayGift.gift_info.total_bonus;
                info.gift_id = firstPayGift.gift_info?.gift_id;
                info.gift_name = firstPayGift.gift_info?.gift_name;

                const betting_bonus = firstPayGift.gift_info.betting_bonus;
                const betting_task = firstPayGift.gift_info.betting_task;
                const day_rewards = firstPayGift.gift_info.day_rewards;

                if (!!betting_bonus && betting_bonus.status === 1) {
                    info.has_bonus = true;
                }

                if (!!betting_task && betting_task.status === 1) {
                    info.has_bonus = true;
                }

                if (!!day_rewards && day_rewards.status === 1) {
                    info.has_bonus = true;
                }

                Object.assign(info, firstPayGift.gift_info)
            }
        }
        return info;
    }

    const checkFirstPayGift = () => {
        let { time_left, has_purchased } = getFirstPayGiftInfo();
        return time_left > 0 && !has_purchased;
    }

    return {
        startPayingOrder,
        getPaymentOrder,
        getPaymentConfig,
        getWithdrawConfig,
        getFirstPayGiftInfo,
        checkFirstPayGift,
    }
}


export default usePaymentActions;