import { useEffect, useState } from 'react';
import styles from './styles.module.scss';
import LazyImage from '@components/LazyImage';
import cashIcon from "@assets/cash_app.webp";
import paypalIcon from "@assets/paypal.webp";
import SvgIcon from '@components/SvgIcon';
import { Swiper, SwiperSlide } from 'swiper/react';
import { Autoplay } from 'swiper/modules';
import { Controller, useForm } from 'react-hook-form';
import { useDispatch, useSelector } from 'react-redux';
import { getFreeWithdraw, getIsBindPhone, getIsGuest, getUserID } from '@features/mainSlice';
import { Checkbox, ToggleButton } from '@mui/material';
import { getWDSetInfoStatus, getWithdrawBaseInfo, getWithdrawInfo } from '@features/paySlice';
import { reqWithdrawBaseInfo, reqWithdrawInfo, reqWithdrawSetInfo } from '@features/api';
import { REQ_STATUS } from '@api/config';
import SmallLoading from '@components/SmallLoading';
import { WithdrawUsers } from '@constants/virtualUser';
import { isFrequentTap, waitForSeconds } from '@utils/helpers';
const i18n = global.i18n;

const Methods = [
    { name: "Cash App", icon: cashIcon },
    { name: "PayPal", icon: paypalIcon },
];

const BtnSubmit = ({ disabled, loading }) => {
    return (
        <button className={styles.button} disabled={disabled}>
            {
                loading ? <SmallLoading fill='#fff' /> : <>Withdraw</>
            }
        </button>
    );
};

const CashAppTable = ({ accountInfo, active, onSubmit, loading }) => {
    const userName = accountInfo == null ? "" : accountInfo.BankUserName;
    const cashTag = accountInfo == null ? "" : accountInfo.PixNum;
    const { register, handleSubmit, formState: { isValid, isDirty, errors, isSubmitting }, control, reset } = useForm({
        mode: 'onChange',
        defaultValues: {
            appName: userName,
            cashTag: cashTag,
        }
    });

    useEffect(() => {
        reset({
            appName: userName,
            cashTag: cashTag,
        });
    }, [userName, cashTag, reset]);

    return (
        <form key="cash_app_table" autoComplete="off" className={`${styles.table}  ${active ? "" : styles.disable}`} onSubmit={handleSubmit((data) => {
            onSubmit && onSubmit(data);
        })} >
            <Controller control={control}
                name='appName'
                rules={{ required: true }}
                render={({ field: { ref, onChange, value }, fieldState: { error } }) => {
                    return (
                        <div className={styles.table_item}>
                            <input
                                className={styles.item_box}
                                autoComplete="off"
                                placeholder={i18n.t("withdrawInfo.cash_app.app_name")}
                                ref={ref}
                                onChange={e => onChange(e.target.value)}
                                {...register("appName")} />
                            <SvgIcon className={styles.item_icon} herf={"icon_people2"}></SvgIcon>
                        </div>
                    );
                }}
            />

            <Controller control={control}
                name='cashTag'
                rules={{ required: true, minLength: 0, maxLength: 50 }}
                render={({ field: { ref, onChange, value }, fieldState: { error } }) => {
                    return (
                        <>
                            <div className={styles.table_item}>
                                <span className={styles.item_lbl}>$</span>
                                <input
                                    className={styles.item_box}
                                    autoComplete="off"
                                    placeholder={i18n.t("withdrawInfo.cash_app.cash_tag")}
                                    ref={ref}
                                    maxLength={50}
                                    onChange={e => onChange(e.target.value)}
                                    {...register("cashTag")} />
                                <SvgIcon className={styles.item_icon} herf={"icon_book"}></SvgIcon>
                            </div>
                            {/* {error && (error.type === 'minLength' || error.type === 'maxLength') && (
                                <div style={{ color: 'red', fontSize: '0.875rem', marginTop: '0.25rem' }}>
                                    Cash Tag must be exactly 10 characters.
                                </div>
                            )} */}
                        </>
                    );
                }}
            />

            <BtnSubmit disabled={!isValid || isSubmitting} loading={loading} />
        </form>
    );
};

const PayPalTable = ({ accountInfo, active, onSubmit, loading }) => {
    const email = accountInfo == null ? "" : accountInfo.EmailAddress;
    const { register, handleSubmit, formState: { isValid, isDirty, errors, isSubmitting }, control, reset } = useForm({
        mode: 'onChange',
        defaultValues: {
            email: email
        }
    });

    useEffect(() => {
        reset({
            email: email
        });
    }, [email, reset]);

    return (
        <form key="paypal_table" autoComplete="off" className={`${styles.table}  ${active ? "" : styles.disable}`} onSubmit={handleSubmit((data) => {
            onSubmit && onSubmit(data);
        })} >
            <Controller control={control}
                name='email'
                rules={{
                    required: true,
                    pattern: {
                        value: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
                        message: i18n.t("withdrawInfo.paypal.email_invalid") || "Invalid email format"
                    }
                }}
                render={({ field: { ref, onChange, value }, fieldState: { error } }) => {
                    return (
                        <div className={styles.table_item}>
                            <input
                                className={styles.item_box}
                                autoComplete="off"
                                type="email"
                                placeholder={i18n.t("withdrawInfo.paypal.placeholder")}
                                ref={ref}
                                onChange={e => onChange(e.target.value)}
                                {...register("email")} />
                            <SvgIcon className={styles.item_icon} herf={"icon_Mail"}></SvgIcon>
                        </div>
                    );
                }}
            />

            <BtnSubmit disabled={!isValid || isSubmitting} loading={loading} />
        </form>
    );
};

// onConfirm(type) type: 0 绑定手机 1 CashApp 2 Paypal
const WWithdrawalInfo = ({ onConfirm, togType = 1, swiper = true, showTog = true, loading = false }) => {
    const [viewType, setViewType] = useState(0);
    const isBind = useSelector(getIsBindPhone);
    const freeWithdraw = useSelector(getFreeWithdraw);
    const baseInfo = useSelector(getWithdrawBaseInfo);
    const infoSetStatus = useSelector(getWDSetInfoStatus);
    const dispatch = useDispatch();

    useEffect(() => {
        if (baseInfo == null) {
            dispatch(reqWithdrawBaseInfo());
        }
    }, [baseInfo]);

    const checkBindPhone = () => {
        if (isBind) return true;
        global.clearPopupFlow();
        global.showBindPhone((success) => {
            if (success) onConfirm && onConfirm(0);
        });
    };

    const checkWithdraw = () => {
        if (!checkBindPhone()) return false;
        return true;
    };

    const checkUpdateAccount = (pixType) => {
        if (baseInfo == null) return true;
        if (baseInfo.PixType != pixType) return true;
        return false;
    };

    const onSubmitCashApp = async (data) => {
        // adjust 点击大厅提款页任意按钮
        global.tracker.trackEvent("click_withdraw_page_any", [{ key: 2, value: "点击CashPay提现" }]);

        if (isFrequentTap("withdrawal_info_cash_app")) return;
        if (IsLoading()) return;
        let params = {};
        params.PixType = 1;
        params.userName = data.appName;
        params.PixNum = data.cashTag;

        if (checkUpdateAccount(1) || baseInfo.BankUserName != params.userName || baseInfo.PixNum != params.PixNum) {
            console.warn("更新CashApp资料");
            await dispatch(reqWithdrawSetInfo(params)).unwrap();
            // if (res.code == 200) {
            //     global.withdrawRes && global.withdrawRes(true);
            // }
        }

        if (!checkWithdraw()) return;
        onConfirm && onConfirm(1);
    };

    const onSubmitPaypal = async (data) => {
        // adjust 点击大厅提款页任意按钮
        global.tracker.trackEvent("click_withdraw_page_any", [{ key: 3, value: "点击Paypal提现" }]);

        if (isFrequentTap("withdrawal_info_pay_pal")) return;
        if (IsLoading()) return;
        let params = {};
        params.PixType = 2;
        params.email = data.email;

        if (checkUpdateAccount(2) || baseInfo.EmailAddress != data.email) {
            console.warn("更新Paypal资料");
            await dispatch(reqWithdrawSetInfo(params)).unwrap();
            // if (res.code == 200) {
            //     global.withdrawRes && global.withdrawRes(true);
            // }
        }

        if (!checkWithdraw()) return;
        onConfirm && onConfirm(2);
    };

    const onTogClick = (index) => {
        // adjust 点击大厅提款页任意按钮
        global.tracker.trackEvent("click_withdraw_page_any", [{ key: index, value: index ? "选择Paypal" : "选择CashPay" }]);
        if (infoSetStatus === REQ_STATUS.LOADING) return;
        setViewType(index);
    };

    const renderBlockTog = (index, item) => {
        return (
            <div key={`withdraw_way_block_${index}`} className={`${styles.block_tog}  ${viewType == index ? styles.tog_active : ""}`} onClick={() => { onTogClick(index); }}>
                <LazyImage className={styles.icon} src={item.icon} alt={item.name}></LazyImage>
                {item.name}
            </div>
        );
    };

    const renderRoundedTog = (index, item) => {
        return (
            <div key={`withdraw_way_round_${index}`} className={`${styles.round_tog}  ${viewType == index ? styles.tog_active : ""}`} onClick={() => { onTogClick(index); }}>
                <div className={styles.circle}>
                    {viewType === index && <SvgIcon herf={"icon_Check"} className={styles.flag}></SvgIcon>}
                </div>
                <div className={styles.label}>{item.name}</div>
            </div>
        );
    };

    const getToggleStyle = (index, item) => {
        switch (togType) {
            case 1: return renderRoundedTog(index, item);
            default:
                return renderBlockTog(index, item);
        }
    };

    const renderToggles = () => {
        return (
            <div className={styles.tog_box}>
                {Methods.map((item, index) => getToggleStyle(index, item))}
            </div>
        );
    };

    const IsLoading = () => {
        return infoSetStatus === REQ_STATUS.LOADING || loading;
    };

    return (
        <div className={styles.container}>
            {showTog && renderToggles()}
            <CashAppTable accountInfo={baseInfo} active={viewType === 0} onSubmit={onSubmitCashApp} loading={IsLoading()} />
            <PayPalTable accountInfo={baseInfo} active={viewType === 1} onSubmit={onSubmitPaypal} loading={IsLoading()} />

            {swiper && <Swiper
                direction="vertical"
                autoplay={{ delay: 1500 }}
                loop
                modules={[Autoplay]}
                className={styles.swiper_box}>
                {WithdrawUsers.map((item, i) => (
                    <SwiperSlide key={i}>
                        <div>
                            {item.messages}
                            <span className={styles.swiper_money}>{` $${item.money}`}</span>
                        </div>
                    </SwiperSlide>
                ))}
            </Swiper>
            }
        </div>
    );
};
export default WWithdrawalInfo;
