import SvgIcon from '@components/SvgIcon';
import styles from './styles.module.scss';
import img_cashApp from '@assets/pay/cash_app.webp';
import img_apple from "@assets/pay/apple_pay.png";
import img_google from "@assets/pay/google_pay.png";
import { useEffect, useRef, useState } from 'react';
import usePaymentActions from '@hooks/usePaymentActions';
import { useSelector } from 'react-redux';
import { getCurrPayOrder, getPaymentOrderStatus } from '@features/paySlice';
import { REQ_STATUS } from '@api/config';
import SmallLoading from '@components/SmallLoading';
import { useNavigate } from 'react-router';
import { ROUTE_PATH } from '@constants/routes';
import { isEmptyOrNull, isIOS } from '@utils/helpers';
import Popup from '@components/Popup';

const i18n = global.i18n;

const CashApp = ({ active, onClick }) => {
    return (
        <div className={`${active ? styles.item_box_active : styles.item_box}`} onClick={onClick}>
            <img src={img_cashApp} />
            <SvgIcon className={styles.svg} herf={"icon_check_circle"} />
        </div>
    )
}

const GooglePay = ({ active, onClick }) => {
    return (
        <div className={`${active ? styles.item_box_active : styles.item_box}`} onClick={onClick}>
            <img src={img_google} />
            <SvgIcon className={styles.svg} herf={"icon_check_circle"} />
        </div>
    )
}

const ApplePay = ({ active, onClick }) => {
    return (
        <div className={`${active ? styles.item_box_active : styles.item_box}`} onClick={onClick}>
            <img src={img_apple} />
            <SvgIcon className={styles.svg} herf={"icon_check_circle"} />
        </div>
    )
}

const Components = {
    "cashapp": CashApp,
    "applepay": ApplePay,
    "googlepay": GooglePay,
}


const WPaymentMethods = () => {
    const goods = global.curGoods || {};
    const methods = JSON.parse(goods.gear || "[]");
    const [dialog, setDialog] = useState(false);
    const [selectId, setSelectId] = useState(0);
    const { getPaymentOrder } = usePaymentActions();
    const orderStatus = useSelector(getPaymentOrderStatus);
    const navigate = useNavigate();

    useEffect(() => {
        // adjust 进入支付控制台
        global.tracker.trackEvent("enter_recharge_control");
        global.tracker.trackEvent("enter_recharge_control_count");
    }, [])

    const onPaid = (order) => {
        global.curPayUrl = order.data.content;
        if (isEmptyOrNull(global.curPayUrl)) {
            console.error('payment url is empty');
            return;
        }
        if (window.Capacitor?.isNativePlatform?.()) {
            window.AndroidAdjust?.openLinkInBrowser?.(global.curPayUrl);
        } else {
            //navigate(ROUTE_PATH.PAYIFRAME);
            // if (newTab) {
            //     newTab.location.href = global.curPayUrl;
            // } else {
            //     navigate(ROUTE_PATH.ORDERCHECK);
            //     window.open(global.curPayUrl)
            // }
            setDialog(true);
        }
        // setPayUrl(url);
        // setShowIFrame(true);
        // console.error(`on Paid url: ${url}`);
    }

    const onBtnPayClick = () => {
        if (orderStatus === REQ_STATUS.LOADING) return;
        goods.pay_method = methods[selectId].value;
        goods.pay_name = methods[selectId].name;
        goods.onCompleted = onPaid;
        getPaymentOrder(goods);
        // adjust 点击支付控制台按钮
        global.tracker.trackEvent("click_recharge_in_control", [{ key: "payName", value: methods[selectId].name }]);
        global.tracker.trackEvent("click_recharge_in_control_count");
    }

    const hideDialog = () => {
        setDialog(false);
    }

    const handleContinue = () => {
        setDialog(false);
        navigate(ROUTE_PATH.ORDERCHECK);
        window.open(global.curPayUrl, "_blank");
    }

    return (
        <>
            <div className={styles.container}>
                <div className={styles.lbl_money}>${goods.price}</div>
                {
                    methods.map((item, index) => {
                        const Com = Components[item.name]
                        if (Com) {
                            return <Com
                                key={`methods_${item.name}`}
                                active={index === selectId}
                                onClick={() => { setSelectId(index) }}
                            />
                        } else {
                            return null;
                        }
                    })
                }

                <button className={styles.btn_pay} onClick={onBtnPayClick}>
                    {
                        orderStatus === REQ_STATUS.LOADING ? <SmallLoading fill='#fff' /> : <>Pay</>
                    }
                </button>
            </div>

            <Popup onClose={hideDialog} open={dialog}>
                <div className={styles.dialog}>
                    <SvgIcon className={styles.icon} herf={'icon_warn'} />
                    <span>{i18n.t("deposit.prompt.title")}</span>
                    <span>{i18n.t("deposit.prompt.content")}</span>

                    <button onClick={handleContinue}>
                        {i18n.t("deposit.prompt.continue")}
                    </button>
                </div>
            </Popup>
        </>

    )
}

export default WPaymentMethods