import React, {useEffect, useRef, useState} from "react";
import {reqMexWithdrawSetInfo, reqRuWithdrawSetInfo, reqWithdrawInfo, reqWithdrawSetInfo} from "@features/api";
import {useDispatch, useSelector} from "react-redux";
import {getUserInfo} from "@features/mainSlice";
import {getWDBaseInfoStatus, getWDInfoStatus, getWDSetInfoStatus, getWithdrawInfo} from "@features/paySlice";
import {useThemeProvider} from "@contexts/themeContext";
import {Controller, useForm} from "react-hook-form";
import {REQ_STATUS} from "@api/config";
import styles from "./styles.module.scss";
import SmallLoading from "@components/SmallLoading";
import Spring from "@components/Spring";
import {validateEmail} from "@utils/helpers";
import SvgIcon from "@components/SvgIcon";
import RadioBtn from "@components/RadioBtn";
import MuiDrawer from "@mui/material/Drawer";
import {Popover} from "@mui/material";

const i18n=global.i18n;
const RUAccountEdit=({close})=>{
    const user=useSelector(getUserInfo);
    const baseStatus=useSelector(getWDBaseInfoStatus);
    const setStatus=useSelector(getWDSetInfoStatus);
    const infoStatus=useSelector(getWDInfoStatus);
    let info=useSelector(getWithdrawInfo);
    let dinfo=info==null?{}:info;
    const dispatch=useDispatch();
    const {isMobile} = useThemeProvider();
    const [showBankSelect, setShowBankSelect] = useState(false);
    const [searchValue, setSearchValue] = useState("");
    const {register, handleSubmit, formState: {errors}, control} = useForm({
        values: {
            account: dinfo.AccountsBank||"",
            userName: dinfo.BankUserName||"",
            bank: dinfo.BranchBank||"",
            branceBank: dinfo.BranchBank||"",
            phone: dinfo.PhoneNumber||"",
            PAN: dinfo.PANNumber||"",
            IFSC:dinfo.IFSCNumber||"",
            email: dinfo.EmailAddress||"",
            PixNum: dinfo.PixNum||"",
            adhaar: dinfo.AdhaarNumber||"",
            PixType: dinfo.PixType||"1",
            bankName:""
        }
    });
    const [showPixType, setShowPixType] = useState(dinfo.PixType||"1");
    const [bankNo, setBankNo] = useState(dinfo.BranchBank||"");
    const selectRef = useRef(null);
    useEffect(()=>{
        dispatch(reqWithdrawInfo({UserID:user.UserID}));
    },[])
    useEffect(()=>{
        if (info!=null){
            setBankNo(info.BranchBank||"");
            setShowPixType(dinfo.PixType||"1")
        }
    },[info])
    const checkLockStatus=()=>{
        if (baseStatus===REQ_STATUS.LOADING)return true;
        if (setStatus===REQ_STATUS.LOADING)return true;
        return false;
    }
    const validateMail=(value)=>{
        return validateEmail(value);
    }
    const validateBankCode=()=>{
        let num=Number(bankNo);
        return num>0;
    }
    const getBankNameFromCode=()=>{
        let bankName="";
        if (info!=null){
            let bank_list=info.bank_list;
            if (bank_list!=null){
                let name=bank_list[bankNo];
                if (name!=null)bankName=name;
            }
        }
        return bankName;
    }
    const showCSelect=()=>{
        setSearchValue("");
        setShowBankSelect(true);
    }
    const hideCSelect=()=>{
        setShowBankSelect(false);
    }
    const getBankCodeList=()=>{
        let list=[];
        if (info!=null){
            let tempS=searchValue.toUpperCase();
            let bank_list=info.bank_list;
            if (bank_list!=null){
                for (const key in bank_list) {
                    let value=bank_list[key];
                    if (tempS!==""){
                        let temp=value.replaceAll(" ","");
                        temp=temp.toUpperCase();
                        if (temp.indexOf(tempS)!==-1)list.push({code:key,value:value});
                    }
                    else list.push({code:key,value:value});
                }
            }
        }
        list.sort((a, b) => {
            const valueA = a.value;
            const valueB = b.value;

            if (valueA < valueB) {
                return -1;
            }
            if (valueA > valueB) {
                return 1;
            }
            return 0;
        });
        return list;
    }
    const callback=(data)=>{
        if (data&&data.code===200){
            // dispatch(reqWithdrawBaseInfo(callbackBase));
            close();
        }
    }
    const handleChange=(data)=>{
        if (checkLockStatus())return;
        data.bank=bankNo;
        data.callback=callback;
        dispatch(reqRuWithdrawSetInfo(data));
    }
    const renderAccoutForm=()=>{
        return (
            <form autoComplete="off" className={styles.accout_form} onSubmit={handleSubmit((data) => {
                handleChange(data);
            })}>
                {
                    <Controller control={control}
                                name="userName"
                                rules={{required: true}}
                                render={({field: {ref, onChange, value}, fieldState: {error}}) => (
                                    <div className={styles.form_item}>
                                        <div className={styles.title}>{i18n.t("withdraw.account_ru.userName")}</div>
                                        <div className={`input-control ${error ? 'input-control--error' : ''}`}>
                                            <input
                                                value={value}
                                                onChange={e => onChange(e.target.value)}
                                                placeholder={i18n.t('withdraw.account_ru.name_holder')}
                                                ref={ref}
                                            />
                                        </div>
                                    </div>
                                )}
                    />
                }
                <Controller control={control}
                            name="PixType"
                            rules={{required: true}}
                            render={({field: {ref, onChange, value}, fieldState: {error}}) => (
                                <div className={styles.form_item}>
                                    <div className={styles.title}>{i18n.t("withdraw.account_ru.withdraw_via")}</div>
                                    <div className={styles.pix_con}>
                                        <RadioBtn className={styles.radio_type} selected={(value + "") === "1"}
                                                  value={"1"} onChange={(value) => {
                                            setShowPixType(value)
                                            onChange(value);
                                        }}>
                                            <span>{i18n.t("withdraw.account_ru.pix_type_1")}</span>
                                        </RadioBtn>
                                        <RadioBtn className={styles.radio_type} selected={(value + "") === "2"}
                                                  value={"2"} onChange={(value) => {
                                            setShowPixType(value)
                                            onChange(value);
                                        }}>
                                            <span>{i18n.t("withdraw.account_ru.pix_type_2")}</span>
                                        </RadioBtn>
                                    </div>
                                </div>
                            )}
                />
                {
                    showPixType==="1"?(<></>):(
                        <Controller control={control}
                                    name="phone"
                                    rules={{required: true}}
                                    render={({field: {ref, onChange, value}, fieldState: {error}}) => (
                                        <div className={styles.form_item}>
                                            <div className={styles.title}>{i18n.t("withdraw.account_ru.phone")}</div>
                                            <div className={`input-control ${error ? 'input-control--error' : ''}`}>
                                                <input
                                                    value={value}
                                                    type={"tel"}
                                                    onChange={e => onChange(e.target.value)}
                                                    placeholder={i18n.t('withdraw.account_ru.phone_holder')}
                                                    ref={ref}
                                                />
                                            </div>
                                        </div>
                                    )}
                        />
                    )
                }
                {
                    showPixType==="1"?(
                        <Controller control={control}
                                    name="account"
                                    rules={{required: true,maxLength:16,minLength:16}}
                                    render={({field: {ref, onChange, value}, fieldState: {error}}) => (
                                        <div className={styles.form_item}>
                                            <div className={styles.title}>{i18n.t("withdraw.account_ru.tedCon")}</div>
                                            <div className={`input-control ${error ? 'input-control--error' : ''}`}>
                                                <input
                                                    value={value}
                                                    onChange={e => onChange(e.target.value)}
                                                    placeholder={i18n.t('withdraw.account_ru.tedCon_holder')}
                                                    ref={ref}
                                                />
                                            </div>
                                        </div>
                                    )}
                        />
                    ):(<></>)
                }
                {
                    showPixType==="1"?(<></>):(
                    // (
                        <Controller control={control}
                                    name="bankName"
                                    rules={{validate: validateBankCode}}
                                    render={({field: {ref, onChange, value}, fieldState: {error}}) => {
                                        let bname = getBankNameFromCode();
                                        return (
                                            <div className={styles.form_item}>
                                                <div className={styles.title}>{i18n.t("withdraw.account_ru.tedBan")}</div>
                                                <button ref={selectRef} type={"button"}
                                                        className={`input-control ${styles.btn_bank} ${error ? 'input-control--error' : ''}`}
                                                        onClick={() => {
                                                            showCSelect();
                                                        }}
                                                >
                                                    <input
                                                        disabled
                                                        value={bname}
                                                        onChange={e => onChange(e.target.value)}
                                                        placeholder={i18n.t('withdraw.account_ru.tedBan_holder')}
                                                        ref={ref}
                                                    />
                                                    <div className={styles.icon_btn}>
                                                        <SvgIcon className={styles.arrow} herf={"icon_Arrow"}></SvgIcon>
                                                    </div>
                                                </button>
                                            </div>
                                        )
                                    }}
                        />
                    )
                }

                <button className={`button-green ${styles.btn_save}`}>
                    {checkLockStatus() ? (
                        <SmallLoading fill={"#FFF"}></SmallLoading>) : i18n.t("withdraw.account.btn_save")}
                </button>
            </form>
        )
    }
    const renderSearch = () => {
        return (
            <div className={`input-control ${styles.select_search}`}>
                <SvgIcon className={styles.icon} herf={"icon_Search"}></SvgIcon>
                <input onChange={e => setSearchValue(e.target.value)}/>
            </div>
        )
    }
    const renderHeader=()=>{
        return (
            <div className={styles.header}>
                {i18n.t("withdraw.account_mx.s_title")}
            </div>
        )
    }
    const renderBankCodeList=()=>{
        let list=getBankCodeList();
        return (
            <div className={styles.select_list_con}>
                {
                    list.map((item,index)=>{
                        return (
                            <button key={index} className={`${styles.item} ${(bankNo+"")===item.code?styles.active:''}`} onClick={()=>{
                                setBankNo(item.code);
                                hideCSelect();
                            }}>
                                <div className={styles.left}>
                                    <span className={styles.name}>{item.value}</span>
                                </div>
                                <RadioBtn selected={(bankNo+"")===item.code} value={item.value} onChange={(value)=>{
                                    setBankNo(item.code);
                                    hideCSelect();
                                }} />
                            </button>
                        )
                    })
                }
            </div>
        )
    }
    const renderMobileBankSelect=()=>{
        return (
            <MuiDrawer open={showBankSelect}
                       anchor={"bottom"}
                       sx={{
                           zIndex:1300,
                           "& .MuiDrawer-paper": {
                               height: "50%",
                               boxSizing: "border-box",
                               overflow: 'visible !important',
                               backgroundColor: 'var(--widget);',
                               boxShadow: 'var(--widget-shadow);',
                               borderTopLeftRadius: '1rem',
                               borderTopRightRadius: '1rem',
                           },
                       }}
                       variant="temporary"
                       onClose={() => {
                           setShowBankSelect(false);
                       }}>
                <div className={`${styles.select_bank_con} ${styles.select_bank_con_m}`}>
                    {renderHeader()}
                    {renderSearch()}
                    {renderBankCodeList()}
                </div>
            </MuiDrawer>
        )
    }
    const renderDeskBankSelect=()=>{
        return (
            <Popover
                open={showBankSelect}
                anchorEl={selectRef.current}
                onClose={()=>{
                    hideCSelect();
                }}
                anchorOrigin={{
                    vertical: 45,
                    horizontal: 0,
                }}
                sx={{
                    "& .MuiPopover-paper": {
                        backgroundColor:'var(--widget);',
                        borderRadius:'var(--border-radius);',
                        width:'22rem;',
                        height:'20rem;',
                        boxShadow:'var(--widget-shadow);'
                    }
                }}
            >
                <div className={styles.select_bank_con}>
                    {renderSearch()}
                    {renderBankCodeList()}
                </div>
            </Popover>
        )
    }
    const renderBankSelect=()=>{
        if (isMobile())return renderMobileBankSelect();
        else return renderDeskBankSelect();
    }
    return (
        <>
            {
                infoStatus === REQ_STATUS.LOADING ? (
                    <div className={styles.loading}>
                        <SmallLoading/>
                    </div>
                ) : (
                    <Spring type="slideUp" className={styles.container}>
                        {renderAccoutForm()}
                        {renderBankSelect()}
                    </Spring>
                )
            }
        </>
    )
}
export default RUAccountEdit;