import Spring from "@components/Spring";
import styles from "./styles.module.scss";
import React, {useState, useEffect} from "react";
import {useDispatch, useSelector} from "react-redux";
import {getUserInfo} from "@features/mainSlice";
import {formatCash, formatCurrency, numFormatter, stringFormat} from "@utils/helpers";
import {getWDPayoutStatus, getWithdrawBaseInfo, getWithdrawInfo} from "@features/paySlice";
import symbol from "@assets/symbol-defs.svg";
import {ReactComponent as Edit} from '@assets/singlesvg/edit.svg';
import {useNavigate} from "react-router-dom";
import {ROUTE_PATH} from "@constants/routes";
import WDPassBox from "@widgets/WWithdraw/PassBox/WDPassBox";
import SmallLoading from "@components/SmallLoading";
import {reqWithdrawBaseInfo, reqWithdrawInfo, reqWithdrawPayout} from "@features/api";
import {REQ_STATUS} from "@api/config";
import {toast} from "react-toastify";
import {APP_COUNTRY_CODE} from "@constants/app";
const i18n=global.i18n;
const BRWithdraw=()=>{
    const user=useSelector(getUserInfo);
    const info=useSelector(getWithdrawBaseInfo);
    const navigate=useNavigate();
    // let addBtnParam = [200, 500, 1000, 2000, 5000, -1];
    const [addBtnParam, setAddBtnParam] = useState([200, 500, 1000, 2000, 5000, -1]);
    const [addIndex,setAddIndex]=useState(-1);
    const [wdValue,setWdValue]=useState("");
    const [wdPass,setWdPass]=useState("");
    const [openPassBox,setOpenPassBox]=useState(false);
    const dispatch = useDispatch();
    const status=useSelector(getWDPayoutStatus);
    const accountInfo=useSelector(getWithdrawInfo);
    const areaItem=global.getLocalAreaItem();
    useEffect(()=>{
       // if (info==null){
       //     dispatch(reqWithdrawBaseInfo())
       // }
        dispatch(reqWithdrawBaseInfo());
        if (areaItem.code===APP_COUNTRY_CODE.MX){
            if (accountInfo==null){
                dispatch(reqWithdrawInfo({UserID:user.UserID}));
            }
        }
        else if (areaItem.code===APP_COUNTRY_CODE.RU){
            if (accountInfo==null){
                dispatch(reqWithdrawInfo({UserID:user.UserID}));
            }
        }
    },[])
    useEffect(()=>{
        let addValues=[200, 500, 1000, 2000, 5000, -1];
        if (info!=null){
            let srate=Number(info.srate);
            for (let i = 0; i < addValues.length; i++) {
                if (addValues[i]!==-1)addValues[i]=addValues[i]*srate;
            }
            setAddBtnParam(addValues);
        }
    },[info])
    const checkBank=()=>{
        if (info!=null){
            // data.BankUserName, data.AccountsBank, data.cbPixType
            let name=info.BankUserName;
            let tname=info.AccountsBank;
            let type=info.type;
            return ((name != "") || (tname != "")) && (type != 0);
        }
        return false;
    }
    const onClickPayout=()=>{
        if (status===REQ_STATUS.LOADING)return;
        if (wdValue===""){
            toast.error(i18n.t("withdraw.main.score_null"),{toastId:"wd_null"})
            return;
        }
        if (!checkBank()){
            toast.error(i18n.t("withdraw.main.unbound_account"),{toastId:"wd_unbound"})
            return;
        }
        let inputNum = Number(wdValue)*global.CASH_BASE;
        let lnum = info.OrderLimit - info.OrderCount;
        // data.WithDrawMin, data.WithDrawMax
        let min=info.MinExchange;
        let max=info.MaxExchange;
        let maxEx=Number(info.SumCanExchange);
        if (inputNum<min){
            toast.error(stringFormat(i18n.t("withdraw.tip.under_can_score"),[formatCash(min,0)]),{toastId:"wd_under"})
            return;
        }
        if (inputNum>max){
            toast.error(stringFormat(i18n.t("withdraw.tip.over_can_score"),[formatCash(max,0)]),{toastId:"wd_over"})
            return;
        }
        if (inputNum>maxEx){
            toast.error(i18n.t("withdraw.tip.total_not_enough"),{toastId:"wd_over"})
            return;
        }
        if (lnum<=0){
            return;
        }
        let num=Number(wdValue);
        if (num>0){
            dispatch(reqWithdrawPayout({
                score:num
            }))
        }
    }
    const getShowCash=(value)=>{
        value=Number(value);
        return value/global.CASH_BASE;
    }
    const formatInput=(text)=>{
        let Score=user.Score*global.CASH_BASE;
        let inputNum = Number(text)*global.CASH_BASE;
        inputNum = Math.min(inputNum, info.SumCanExchange);
        inputNum = Math.min(inputNum, Score);
        return (inputNum > 0) ? (getShowCash(inputNum)) : "";
    }
    const getAddIndexFromValue=(value)=>{
        value=Number(value);
        let index=addBtnParam.indexOf(value);
        if (index===-1){
            if (value===info.CanWithDraw){
                index=addBtnParam.length-1;
            }
        }
        return index;
    }
    const getAccountInfo=()=>{
        let via="";
        let accout="";
        if (areaItem.code===APP_COUNTRY_CODE.MX){
            let AccountsBank=info.AccountsBank;
            let BranchBank=info.BranchBank;
            if (AccountsBank!=null&&AccountsBank!=="")accout=AccountsBank;
            if (BranchBank!=null&&BranchBank!==""){
                if (accountInfo!=null){
                    let bank_list=accountInfo.bank_list;
                    if (bank_list!=null){
                        via=bank_list[BranchBank];
                    }
                }
                else via=BranchBank;
            }
        }
        else if (areaItem.code===APP_COUNTRY_CODE.RU){
            let AccountsBank=info.AccountsBank;
            let PhoneNumber=info.PhoneNumber;
            let PixType=info.PixType;
            let BranchBank=info.BranchBank;
            if (PixType==="1"){
                if(AccountsBank!=null&&AccountsBank!=="")accout=AccountsBank;
                via=i18n.t("withdraw.account_ru.pix_type_1");
            }
            else if (PixType==="2")
            {
                if(PhoneNumber!=null&&PhoneNumber!=="")accout=PhoneNumber;
                via=i18n.t("withdraw.account_ru.pix_type_2")
            }
        }
        else
        {
            if (info!=null){
                let BankUserName=info.BankUserName;
                let AccountsBank=info.AccountsBank;
                let cbPixType=Number(info.PixType);
                if (BankUserName!==""||AccountsBank!==""){
                    via=cbPixType >= 10 ? "TED" : "PIX";
                    accout=cbPixType >= 10 ? AccountsBank : BankUserName
                }
            }
        }
        return {via,accout};
    }
    const renderUser=()=>{
        return (
            <div className={styles.content}>
                <div className={styles.user_con}>
                    <div className={styles.money_con}>
                        <div className={styles.title}>{i18n.t("withdraw.main.total_balance")}</div>
                        <div className={styles.money}>{global.DOLLAR+" "+numFormatter(user.Score)}</div>
                    </div>
                    <div className={styles.money_con}>
                        <div className={styles.title}>{i18n.t("withdraw.main.withdrawable")}</div>
                        <div className={styles.money}>{global.DOLLAR+" "+numFormatter(getShowCash(info.SumCanExchange))}</div>
                    </div>
                </div>
                <div className={styles.line}/>
            </div>
        )
    }
    const renderWithdrawValue=()=>{
        // let locales=global.getLocalAreaAlCode();
        let locales=i18n.getCurrLangKey();
        return (
            <div className={styles.content}>
                <div className={styles.title}>{i18n.t("withdraw.main.editBox")}</div>
                <div className={styles.select_con}>
                    {
                        addBtnParam.map((item,index)=>{
                            let label=item===-1?i18n.t("withdraw.main.btn_all"):global.DOLLAR+" "+formatCurrency(item,locales);
                            return (
                                <button key={index}
                                        className={`${styles.grid_btn} ${addIndex===index?styles.active:''}`}
                                        onClick={()=>{
                                            let value=item===-1?getShowCash(info.SumCanExchange)+"":item+"";
                                            let fvalue=formatInput(value);
                                            let addIndx=Number(value)===fvalue?index:-1;
                                            if (addIndx!==-1)setWdValue(fvalue);
                                            setAddIndex(addIndx);
                                        }}
                                >
                                    {label}
                                </button>
                            )
                        })
                    }
                </div>
                <div className={`input-control ${styles.input_con}`}>
                    <div className={styles.money}>{global.DOLLAR}</div>
                    <input
                        value={wdValue}
                        type={"number"}
                        placeholder={i18n.t("withdraw.main.editPlaceholder")}
                        onChange={(e)=>{
                            // let value=formatInput(e.target.value);
                            // setWdValue(value);
                            // setAddIndex(getAddIndexFromValue(value));
                            setWdValue(e.target.value);
                        }}
                    />
                    {
                        wdValue===""?(<></>):(
                            <button className={styles.clear_btn} onClick={()=>{
                                setWdValue("");
                            }}>
                                <svg className={styles.icon}>
                                    <use xlinkHref={`${symbol}#icon_Close`} />
                                </svg>
                            </button>
                        )
                    }
                </div>
                <div className={styles.line}/>
            </div>
        )
    }
    const renderAccount=()=>{
        // let BankUserName=info.BankUserName;
        // let AccountsBank=info.AccountsBank;
        // let cbPixType=Number(info.PixType);
        // let via="";
        // let accout="";
        // if (BankUserName!==""||AccountsBank!==""){
        //     via=cbPixType >= 10 ? "TED" : "PIX";
        //     accout=cbPixType >= 10 ? AccountsBank : BankUserName
        // }
        const {via,accout}=getAccountInfo();
        return (
            <div className={`${styles.content} ${styles.account_info}`}>
                <div className={styles.title_con}>
                    <div className={styles.title}>{i18n.t("withdraw.account.title")}</div>
                    <button onClick={()=>{
                        navigate(ROUTE_PATH.ACCOUNT_INFO);
                    }}>
                        <Edit className={styles.icon}/>
                    </button>
                </div>
                <div className={styles.line}></div>
                <div className={styles.info_item}>
                    <div className={styles.title}>{i18n.t("withdraw.main.via")}</div>
                    {
                        via===""?(<div>{i18n.t("withdraw.main.bank_info_isNull")}</div>):(
                            <div className={styles.active}>{via}</div>
                        )
                    }
                    {/*<div className={styles.line}></div>*/}
                </div>
                <div className={styles.info_item}>
                    <div className={styles.title}>{i18n.t("withdraw.main.account")}</div>
                    {
                        accout===""?(<div>{i18n.t("withdraw.main.bank_No_isNull")}</div>):(
                            <div className={styles.active}>{accout}</div>
                        )
                    }
                    {/*<div className={styles.line}></div>*/}
                </div>
            </div>
        )
    }
    const renderSubmit=()=>{
        let num = info.OrderLimit - info.OrderCount;
        // data.WithDrawMin, data.WithDrawMax
        let min=getShowCash(info.MinExchange);
        let max=getShowCash(info.MaxExchange);
        return (
            <div className={styles.content}>
                <button className="button-green" onClick={onClickPayout}>
                    {status===REQ_STATUS.LOADING?(<SmallLoading fill={"#fff"}></SmallLoading>):i18n.t("withdraw.main.btn_withdraw")+"  ("+num+")"}
                    {/*{i18n.t("withdraw.main.btn_withdraw")+"  ("+num+")"}*/}
                </button>
                <div className={styles.tips}>
                    {stringFormat(i18n.t("withdraw.main.tip"),[min,max])}
                </div>
            </div>
        )
    }
    const renderPassBox=()=>{
        return (
            <WDPassBox
                open={openPassBox}
                title={i18n.t("withdraw.pass.pass_box_title")}
                confirmLabel={i18n.t("withdraw.pass.btn_confirm")}
                onClose={()=>{
                    setOpenPassBox(false);
                }}
                onConfirm={(data)=>{
                    if (data!=null){
                        setWdPass(data);
                    }
                }}
            >

            </WDPassBox>
        )
    }
    return (
        <>
            {
                info==null?(<div className={"w-100vw h-100vh"}><SmallLoading /></div>):(
                    <Spring type="slideUp" className={styles.container}>
                        {renderUser()}
                        {renderWithdrawValue()}
                        {renderAccount()}
                        {renderSubmit()}
                        {renderPassBox()}
                    </Spring>
                )
            }
        </>
    )
}
export default BRWithdraw;
