import styles from './styles.module.scss';
import Spring from "@components/Spring";
import {APP_AVATAR, REQ_STATUS} from "@api/config";
import LazyImage from "@components/LazyImage";
import {useDispatch, useSelector} from "react-redux";
import {getChangeEmailStatus, getChangeInfoStatus, getChangePhoneStatus, getUserInfo} from "@features/mainSlice";
import React, {useEffect, useState} from "react";
import {Controller, useForm} from "react-hook-form";
import classNames from "classnames";
import PhoneInput from "@components/UInput/PhoneInput";
import {ReactComponent as Male} from '@assets/singlesvg/gener/male.svg';
import {ReactComponent as FeMale} from '@assets/singlesvg/gener/female.svg';
import SmallLoading from "@components/SmallLoading";
import {reqChangeEmail, reqChangeInfo, reqChangePhone} from "@features/api";
import {APP_GENDER, APP_THEME} from "@constants/app";
import {validateCountryPhone, validateEmail} from "@utils/helpers";
import LazyImgix from "@components/Imgix/LazyImgix";
import {useLocation} from "react-router";
import {ROUTE_PATH} from "@constants/routes";
import logo_dark from '@assets/logo/logo.png';
import logo_light from '@assets/logo/logo_w.png';
import {useThemeProvider} from "@contexts/themeContext";
const i18n=global.i18n;

const TYPE_BASE="base";
const TYPE_PHONE="phone";
const TYPE_EMAIL="email";
const getAvatarUrl=(id)=>{
    return `${APP_AVATAR}avatar_${id}.png?auto=format,compress&cs=srgb`;
}
const SelectAvatar=({innerRef, ...props})=>{
    const [value, setValue] = useState(props.value);
    const aNum=16;
    const avatars = Array.from({ length:aNum }, (value, index) => index + 1);
    return (
        <div className={styles.select_avatar_con}
            ref={innerRef}
            {...props}
        >
            {
                avatars.map((item,index)=>{
                    return (
                        <button type={"button"} key={index} className={`${styles.avatar_btn}`} onClick={()=>{
                            setValue(item);
                            if (props.onChange)props.onChange(item);
                        }}>
                            {/*<LazyImage wrapperClassName={`${styles.avatar} ${item==value?styles.active:''}`} src={getAvatarUrl(item)} alt={"avatar_" + index}/>*/}
                        <LazyImgix className={`${styles.avatar} ${item==value?styles.active:''}`} src={getAvatarUrl(item)} alt={"avatar_" + index} width={60} />
                        </button>
                    )
                })
            }
        </div>
    )
}
const WEditProfile=({close})=>{
    const user=useSelector(getUserInfo);
    const status=useSelector(getChangeInfoStatus);
    const status_ph=useSelector(getChangePhoneStatus);
    const status_em=useSelector(getChangeEmailStatus);
    const dispatch = useDispatch();
    const [avatarID,setAvatarID]=useState(user.FaceID);
    const [country, setCountry] = useState(user.RegisterLocation);
    const [showType,setShowType]=useState(TYPE_BASE);
    const {pathname,hash} = useLocation();
    const {theme,isMobile} = useThemeProvider();
    const logourl=(theme===APP_THEME.DARK?logo_dark:logo_light);
    const validatePhone=(value)=>{
        return validateCountryPhone(country,value);
    }
    const validateMail=(value)=>{
        return validateEmail(value);
    }
    const getPhoneError=()=>{
        if (country==="55")return i18n.t("form_errors.phone_" + country);
        else return i18n.t("form_errors.phone");
    }
    const getPhone=()=>{
        let loc=user.RegisterLocation;
        let phone=user.Phone;
        if (phone.startsWith(loc)){
            phone=phone.replace(loc,"");
        }
        return phone;
    }
    const getIsLock=()=>{
        let isLock=status===REQ_STATUS.LOADING||status_ph===REQ_STATUS.LOADING||status_em===REQ_STATUS.LOADING;
        return isLock;
    }
    const {register, handleSubmit, formState: {errors}, control} = useForm({
        defaultValues: {
            FaceID:user.FaceID,
            NickName:user.NickName,
            Gender:user.Gender,
            Phone:getPhone(),
            Email:user.Email
        }
    });
    useEffect(() => {
        if (hash===ROUTE_PATH.EDIT_PROFILE){
            setShowType(TYPE_BASE);
        }
        else if (hash===ROUTE_PATH.EDIT_PHONE){
            setShowType(TYPE_PHONE);
        }
        else if (hash===ROUTE_PATH.EDIT_EMAIL){
            setShowType(TYPE_EMAIL);
        }
    }, [pathname,hash]);
    const renderAvatar=()=>{
        return (
            <div className={styles.avatar_con}>
                {/*<LazyImage wrapperClassName={styles.avatar} src={getAvatarUrl(avatarID)} alt={"avator"}/>*/}
                <LazyImgix className={styles.avatar} src={getAvatarUrl(avatarID)} alt={"avatar"} width={100}></LazyImgix>
            </div>
        )
    }
    const renderSelectAvatar=()=>{
        return (
            <div className={styles.form_item}>
                <div className={styles.title}>{i18n.t("user.title_avatar")}</div>
                <Controller control={control}
                            name="FaceID"
                            render={({field: {ref, onChange, value}, fieldState: {error}}) => (
                                <SelectAvatar
                                    value={value}
                                    onChange={(faceID)=>{
                                        onChange(faceID);
                                        setAvatarID(faceID);
                                    }}
                                    innerRef={ref}/>
                            )}
                />
            </div>
        )
    }
    const renderUsername=()=>{
        return (
            <div className={styles.form_item}>
                <div className={styles.title}>{i18n.t("user.title_username")}</div>
                <Controller control={control}
                            name="NickName"
                            rules={{required: true}}
                            render={({field: {ref, onChange, value}, fieldState: {error}}) => (
                                <div className={classNames("input-control",{'input-control--error': error})}>
                                    <input
                                           value={value}
                                           type="tel"
                                           ref={ref}
                                           onChange={(e)=>{
                                               onChange(e.target.value);
                                           }}
                                           placeholder={i18n.t('user.username_ph')}
                                    />
                                </div>

                            )}
                />
            </div>
        )
    }
    const renderPhone=()=>{
        return (
            <div className={styles.form_item}>
                <div className={styles.title}>{i18n.t("user.title_phone")}</div>
                <Controller control={control}
                            name="Phone"
                            rules={{required: true,validate:validatePhone}}
                            render={({field: {ref, onChange, value}, fieldState: {error}}) => {
                                let message = error ? getPhoneError() : "";
                                return (
                                    <PhoneInput
                                        className={classNames({'input-control--error': error})}
                                        value={value}
                                        message={message}
                                        onChange={e => onChange(e.target.value)}
                                        onChangeCountry={(country)=>{
                                            setCountry(country);
                                        }}
                                        placeholder={i18n.t('user.phone_ph')}
                                        innerRef={ref}/>

                                )
                            }}
                />
            </div>
        )
    }
    const renderEmail=()=>{
        return (
            <div className={styles.form_item}>
                <div className={styles.title}>{i18n.t("user.title_email")}</div>
                <Controller control={control}
                            name="Email"
                            rules={{validate:validateMail}}
                            render={({field: {ref, onChange, value}, fieldState: {error}}) => (
                                <div className={`d-flex flex-column g-6`}>
                                    <div className={classNames("input-control",{'input-control--error': error})}>
                                        <input
                                            value={value}
                                            ref={ref}
                                            onChange={(e)=>{
                                                onChange(e.target.value);
                                            }}
                                            placeholder={i18n.t('user.email_ph')}
                                        />
                                    </div>
                                    {
                                        error?(<div className="input-prompt-error">{i18n.t('form_errors.email')}</div>):(<></>)
                                    }
                                </div>
                            )}
                />
            </div>
        )
    }
    const renderGender=()=>{
        return (
            <div className={styles.form_item}>
                <div className={styles.title}>{i18n.t("user.title_gender")}</div>
                <Controller control={control}
                            name="Gender"
                    // rules={{required: true}}
                            render={({field: {ref, onChange, value}, fieldState: {error}}) => (
                                <div className={styles.gender_con}>
                                    <button type={"button"} className={`${styles.radio_btn} ${value===APP_GENDER.FEMALE?styles.active:''}`} onClick={()=>{
                                        onChange(APP_GENDER.FEMALE);
                                    }}>
                                        <div className={styles.circle}>
                                            <div className={styles.dot}/>
                                        </div>
                                        <div>{i18n.t("user.female")}</div>
                                        <FeMale className={styles.icon_f}/>
                                    </button>
                                    <button type={"button"} className={`${styles.radio_btn} ${value===APP_GENDER.MALE?styles.active:''}`} onClick={()=>{
                                        onChange(APP_GENDER.MALE)
                                    }}>
                                        <div className={styles.circle}>
                                            <div className={styles.dot}/>
                                        </div>
                                        <div>{i18n.t("user.male")}</div>
                                        <Male className={styles.icon_m}/>
                                    </button>
                                    <button type={"button"} className={`${styles.radio_btn} ${value===APP_GENDER.OTHER?styles.active:''}`} onClick={()=>{
                                        onChange(APP_GENDER.OTHER)
                                    }}>
                                        <div className={styles.circle}>
                                            <div className={styles.dot}/>
                                        </div>
                                        <div>{i18n.t("user.other")}</div>
                                    </button>
                                </div>
                            )}
                />
            </div>
        )
    }
    const renderSubmit=(isTop=true)=>{
        let isLoading=getIsLock();
        return (
            <div className={`${isTop?styles.submit_btn_con:''}`}>
                <button className={"button-green"}>
                    {
                        isLoading?(<SmallLoading fill={"#fff"}/>):i18n.t("user.submit_btn")
                    }
                </button>
            </div>
        )
    }
    const onCallback=(code)=>{
        if (code==200){
            if (close)close();
        }
    }
    const handleChangeInfo=(data)=>{
        data.Phone=country+data.Phone;
        data.RegisterLocation=country;
        let change={};
        let change_ph={};
        let change_em={};
        let isSubmit=false;
        let isSubmit_ph=false;
        let isSubmit_em=false;
        for (const key in data) {
            let value=data[key];
            if (value!==user[key]){
                if (key==="Phone"){
                    isSubmit_ph=true;
                    change_ph[key]=value;
                    change_ph["RegisterLocation"]=country;
                }
                else if (key==="Email"){
                    isSubmit_em=true;
                    change_em[key]=value;
                }
                else
                {
                    isSubmit=true;
                    change[key]=value;
                }
            }
        }
        // if (!isSubmit)return;
        if (getIsLock())return;
        change.callback=onCallback;
        change_ph.callback=onCallback;
        change_em.callback=onCallback;
        if (showType!==TYPE_PHONE)isSubmit_ph=false;
        if (showType!==TYPE_EMAIL)isSubmit_em=false;
        if (isSubmit)dispatch(reqChangeInfo(change));
        // data.callback=onCallback;
        // dispatch(reqChangeInfo(data));
        if (isSubmit_ph)dispatch(reqChangePhone(change_ph));
        if (isSubmit_em)dispatch(reqChangeEmail(change_em));
    }
    const renderForm=()=>{
        return (
            <form key={"base"} autoComplete="off" className={styles.user_form} onSubmit={handleSubmit((data) => {
                handleChangeInfo(data);
            })}>
                {renderUsername()}
                {/*{renderPhone()}*/}
                {/*{renderEmail()}*/}
                {renderGender()}
                {renderSelectAvatar()}
                {renderSubmit()}
            </form>
        )
    }
    const renderEditBase=()=>{
        return (
            <div className={styles.container}>
                <Spring type="slideUp" className={styles.content}>
                    {renderAvatar()}
                    {renderForm()}
                </Spring>
            </div>
        )
    }
    const renderLogo=()=>{
        return (
            <div className={styles.l_logo}>
                <img className={styles.logo_img} src={logourl}/>
            </div>
        )
    }
    const renderEditPhone=()=>{
        return (
            <div className={styles.container}>
                <Spring type="slideUp" className={styles.content}>
                    {renderLogo()}
                    <form key={"phone"} autoComplete="off" className={styles.user_form} onSubmit={handleSubmit((data) => {
                        handleChangeInfo(data);
                    })}>
                        {renderPhone()}
                        {renderSubmit(false)}
                    </form>
                </Spring>
            </div>
        )
    }
    const renderEditEmail=()=>{
        return (
            <div className={styles.container}>
                <Spring type="slideUp" className={styles.content}>
                    {renderLogo()}
                    <form key={"email"} autoComplete="off" className={styles.user_form} onSubmit={handleSubmit((data) => {
                        handleChangeInfo(data);
                    })}>
                        {renderEmail()}
                        {renderSubmit(false)}
                    </form>
                </Spring>
            </div>
        )
    }
    const renderView=()=>{
        if (showType === TYPE_BASE) return renderEditBase();
        else if (showType===TYPE_PHONE)return renderEditPhone();
        else if (showType===TYPE_EMAIL)return renderEditEmail();
        return (<></>);
    }
    return (
        <>
            {renderView()}
        </>
    )
}
export default WEditProfile;
