import React, {useEffect, useState} from "react";
import Popup from "@components/Popup";
import styles from "./styles.module.scss";
import {Controller, useForm} from "react-hook-form";
import classNames from "classnames";
import {validateCountryPhone, validateEmail} from "@utils/helpers";
import {REQ_STATUS} from "@api/config";
import SmallLoading from "@components/SmallLoading";
import PhoneInput from "@components/UInput/PhoneInput";
import {useDispatch, useSelector} from "react-redux";
import {getKycEUStatus, getKycTypes} from "@features/paySlice";
import {reqKycEU} from "@features/api";

const i18n=global.i18n;
const WDepositInfo = ({})=>{
    const [isShow, setIsShow] = useState(false);
    const [country, setCountry] = useState("55");
    const reqKycStatus=useSelector(getKycEUStatus);
    const dispatch = useDispatch();
    //first,last,email,phone,city
    const kycTypes=useSelector(getKycTypes);
    const {register, handleSubmit, formState: {errors}, control} = useForm({
        defaultValues: {
            firstName:'',
            lastName:'',
            phone:'',
            email:'',
            city:''
        }
    });
    const show=(callback)=>{
        global.wdepositInfo.callback=callback;
        setIsShow(true);
    }
    const hide=()=>{
        setIsShow(false);
    }
    useEffect(()=>{
        const wdepositInfo={
            show,
            hide
        };
        global.wdepositInfo=wdepositInfo;
    },[])
    const onCallback=(payload)=>{
        if (payload&&payload.code===200){
            if (global.wdepositInfo.callback)global.wdepositInfo.callback();
            hide();
        }
    }
    const onSubmitInfo=(data)=>{
        if (reqKycStatus===REQ_STATUS.LOADING)return;
        let new_data=data;
        if (data.phone&&data.phone!==""){
            let phone=country+data.phone;
            new_data=Object.assign({},data,{phone:phone});
        }
        dispatch(reqKycEU(new_data)).then((data)=>{
            onCallback(data.payload)
        });
    }
    const validateMail=(value)=>{
        return validateEmail(value);
    }
    const validatePhone=(value)=>{
        return validateCountryPhone(country,value);
    }
    const getPhoneError=()=>{
       return "";
    }
    const renderFirstName=()=>{
        //first,last,email,phone,city
        if (!kycTypes.includes("first")){
            return (<></>);
        }
        return (
            <Controller control={control}
                        name="firstName"
                        rules={{required: true}}
                        render={({field: {ref, onChange, value}, fieldState: {error}}) => (
                            <div className={styles.form_item}>
                                <span className={styles.form_title}>{i18n.t("deposit.infomation.title_firstName")}</span>
                                <div className={classNames("input-control", {'input-control--error': error})}>
                                    <input
                                        value={value}
                                        ref={ref}
                                        onChange={(e) => {
                                            onChange(e.target.value);
                                        }}
                                        placeholder={i18n.t('deposit.infomation.ph_firstName')}
                                    />
                                </div>
                            </div>
                        )}
            />
        )
    }
    const renderLastName = () => {
        //first,last,email,phone,city
        if (!kycTypes.includes("last")){
            return (<></>);
        }
        return (
            <Controller control={control}
                        name="lastName"
                        rules={{required: true}}
                        render={({field: {ref, onChange, value}, fieldState: {error}}) => (
                            <div className={styles.form_item}>
                                <span className={styles.form_title}>{i18n.t("deposit.infomation.title_lastName")}</span>
                                <div className={classNames("input-control", {'input-control--error': error})}>
                                    <input
                                        value={value}
                                        ref={ref}
                                        onChange={(e) => {
                                            onChange(e.target.value);
                                        }}
                                        placeholder={i18n.t('deposit.infomation.ph_lastName')}
                                    />
                                </div>
                            </div>
                        )}
            />
        )
    }
    const renderEmail = () => {
        //first,last,email,phone,city
        if (!kycTypes.includes("email")){
            return (<></>);
        }
        return (
            <Controller control={control}
                        name="email"
                        rules={{required: true, validate: validateMail}}
                        render={({field: {ref, onChange, value}, fieldState: {error}}) => (
                            <div className={styles.form_item}>
                                <span className={styles.form_title}>{i18n.t("deposit.infomation.title_email")}</span>
                                <div className={`input-control ${error ? 'input-control--error' : ''}`}>
                                    <input
                                        value={value}
                                        onChange={e => onChange(e.target.value)}
                                        placeholder={i18n.t('deposit.infomation.ph_email')}
                                        ref={ref}
                                    />
                                </div>
                            </div>
                        )}
            />
        )
    }
    const renderCity = () => {
        //first,last,email,phone,city
        if (!kycTypes.includes("city")){
            return (<></>);
        }
        return (
            <Controller control={control}
                        name="city"
                        rules={{required: true}}
                        render={({field: {ref, onChange, value}, fieldState: {error}}) => (
                            <div className={styles.form_item}>
                                <span className={styles.form_title}>{i18n.t("deposit.infomation.title_city")}</span>
                                <div className={classNames("input-control", {'input-control--error': error})}>
                                    <input
                                        value={value}
                                        ref={ref}
                                        onChange={(e) => {
                                            onChange(e.target.value);
                                        }}
                                        placeholder={i18n.t('deposit.infomation.ph_city')}
                                    />
                                </div>
                            </div>
                        )}
            />
        )
    }
    const renderPhone=()=>{
        //first,last,email,phone,city
        if (!kycTypes.includes("phone")){
            return (<></>);
        }
        return (
            <Controller control={control}
                        name="phone"
                        rules={{required: true, validate: validatePhone}}
                        render={({field: {ref, onChange, value}, fieldState: {error}}) => {
                            let message = error ? getPhoneError() : "";
                            return (
                                <div className={styles.form_item}>
                                    <span className={styles.form_title}>{i18n.t("deposit.infomation.title_phone")}</span>
                                    <PhoneInput
                                        className={classNames({'input-control--error': error})}
                                        value={value}
                                        message={message}
                                        onChange={e => onChange(e.target.value)}
                                        onChangeCountry={(country) => {
                                            setCountry(country);
                                        }}
                                        placeholder={i18n.t('deposit.infomation.ph_phone')}
                                        innerRef={ref}/>
                                </div>
                            )
                        }}/>
        )
    }
    return (
        <Popup onClose={()=>{
            hide();
        }} open={isShow}>
            <div className={styles.container}>
                <span className={styles.title}>{i18n.t("deposit.infomation.modifyInfoTitle")}</span>
                <form autoComplete="off" className={styles.l_form} onSubmit={handleSubmit((data) => {
                    onSubmitInfo(data);
                })}>
                    {renderFirstName()}
                    {renderLastName()}
                    {renderPhone()}
                    {renderEmail()}
                    {renderCity()}
                    <button className={`button-green ${styles.form_submit}`}>
                        {reqKycStatus===REQ_STATUS.LOADING?(<SmallLoading fill={"#fff"}/>):i18n.t("deposit.infomation.btn_confirm")}
                    </button>
                </form>
                <span className={styles.tips}>{i18n.t("deposit.infomation.info_tips")}</span>
            </div>
        </Popup>
    )
}
export default WDepositInfo;
