// hooks
import { useForm, Controller } from 'react-hook-form';
import React, { useState } from 'react';
import styles from './styles.module.scss';
// utils
import classNames from 'classnames';
import PhoneInput from "@components/UInput/PhoneInput";
import { useDispatch, useSelector } from "react-redux";
import {
    getSendCodeStatus,
    getSendCodeTS,
} from "@features/mainSlice";
import { useEffect } from 'react';
import SmallLoading from "@components/SmallLoading";
import { REQ_STATUS } from "@api/config";
import { reqSendCode } from "@features/api";
import { validateCountryPhone } from "@utils/helpers";
import { CircularProgress } from "@mui/material";
import area from "@db/area";
import SvgIcon from "@components/SvgIcon";
import { toast } from 'react-toastify';

const i18n = global.i18n;
const TYPE_LOGIN = "login";
const TYPE_REGISTER = "register";
const TYPE_FORGET_PASS = "forgetPassword";

const LOGIN_TYPE_PHONE = 0;
const LOGIN_TYPE_SMS = 1;
const LOGIN_TYPE_ID = 2;
const LOGIN_TYPE_MAIL = 3;
const LOGIN_TYPE_GUEST = 4;

const REG_TYPE_PHONE = 0;
const REG_TYPE_SMS = 1;
const REG_TYPE_ID = 2;
const REG_TYPE_MAIL = 3;
const REG_TYPE_GUEST = 4;
const objInfo = {
    cdTimer: null,
    inSubmit: false
}

const CODE_MIN = 4;
const CODE_MAX = 4;

const PhoneSMS = ({ children, callback, buttonText, handleStatus, onCountryChange }) => {
    const [country, setCountry] = useState("55");
    const [phoneValid, setPhoneValid] = useState(false);
    const [phoneMessage, setPhoneMessage] = useState("");
    const dispatch = useDispatch();
    const { register, handleSubmit, formState: { errors }, control, watch } = useForm({
        defaultValues: {
            // country:'55',
            account: '',
            password: '',
            email: "",
            repassword: "",
            lang: "",
            code: "",
            phone: "",
            newpassword: "",
            renewpassword: ""
        }
    });
    const otpTimeStamp = useSelector(getSendCodeTS);
    const [otpCD, setOtpCD] = useState(-1);
    const otpStatus = useSelector(getSendCodeStatus);
    const onSendCode = (e) => {
        if (otpCD > 0) return;
        if (otpStatus === REQ_STATUS.LOADING) return;
        let phone = control._formValues.phone;
        let validate = validatePhone(phone);
        if (!validate) {
            toast.warn(i18n.t("phoneSms.tips_phone"), { toastId: "phone_sms" });
            control.setError("phone", true);
            return;
        }
        let params = { phone: phone, country: country };
        dispatch(reqSendCode(params));
    }
    const getLeftCD = () => {
        let now = Date.now();
        let delta = now - otpTimeStamp;
        delta = Math.floor(delta / 1000);
        delta = 60 - delta;
        if (delta < 0) return -1;
        else return delta;
    }
    const checkPhone = (value) => {
        const ok = validatePhone(value);
        if (!ok) {
            setPhoneValid(false);
            //setPhoneMessage(getPhoneError());
        } else {
            setPhoneValid(true);
            //setPhoneMessage("");
        }
        return ok;
    }
    const clearTimer = () => {
        if (objInfo.cdTimer != null) {
            clearInterval(objInfo.cdTimer);
            objInfo.cdTimer = null;
        }
    }
    const getPhoneError = () => {
        if (country === "55") return i18n.t("form_errors.phone_" + country);
        else return i18n.t("form_errors.phone");
    }

    //effect_______
    useEffect(() => {
        return () => {
            global.authLockPath = null;
            clearTimer();
            objInfo.inSubmit = false;
        }
    }, [])
    useEffect(() => {
        let left = getLeftCD();
        setOtpCD(left);
        clearTimer();
        if (left > 0) {
            objInfo.cdTimer = setInterval(() => {
                left = getLeftCD();
                setOtpCD(left);
                if (left < 0) {
                    clearTimer();
                }
            }, 1000)
        }
    }, [otpTimeStamp])
    const validatePhone = (value) => {
        return validateCountryPhone(country, value || "");
    }
    const renderLoading = () => {
        return (<SmallLoading fill={"#fff"} />)
    }

    const codeValue = watch("code");
    const phoneValue = watch("phone");
    const getBtnDisabled = () => {
        if (handleStatus === REQ_STATUS.LOADING) return true;
        if (!phoneValid) return true;
        if (!codeValue || codeValue.length !== 4) return true;
        return false;
    }
    const checkFormOnClaim = () => {
        if (!checkPhone(phoneValue)) {
            control.setError("phone", true);
            toast.warn(i18n.t("phoneSms.tips_phone"), { toastId: "phone_sms" });
            return false;
        }

        if (!codeValue || codeValue.length < CODE_MIN || codeValue.length > CODE_MAX) {
            control.setError("code", true);
            toast.warn(i18n.t("phoneSms.tips_info"), { toastId: "phone_sms" });
            return false;
        }
        return true;
    }

    const onSubmitOTPLogin = (data) => {
        if (!checkFormOnClaim()) return;
        //data.phone  data.code
        data.country = country;
        callback && callback(data);
    }
    return (
        <form key={"otp"} autoComplete="off" className={styles.l_form} onSubmit={handleSubmit((data) => {
            onSubmitOTPLogin(data);
        })}>
            <Controller control={control}
                name="phone"
                rules={{ required: true }}
                render={({ field: { ref, onChange, value }, fieldState: { error } }) => {
                    let message = phoneMessage;
                    return (<PhoneInput
                        key={"phone"}
                        className={classNames(styles.input_box, { 'input-control--error': error })}
                        value={value}
                        message={message}
                        onChange={
                            e => {
                                //checkPhone(e.target.value)
                                onChange(e.target.value);
                            }
                        }
                        // onBlur={e => {
                        //     checkPhone(e.target.value);
                        // }}
                        onChangeCountry={(country) => {
                            setCountry(country);
                            if (onCountryChange != null) onCountryChange(country);
                        }}
                        placeholder={i18n.t('login.phone_ph')}
                        innerRef={ref}
                    />)
                }}
            />
            <Controller control={control}
                name="code"
                rules={{ required: true, minLength: CODE_MIN, maxLength: CODE_MAX }}
                render={({ field: { ref, onChange, value }, fieldState: { error } }) => {
                    return (
                        <div className={`d-flex flex-column g-6`}>
                            <div
                                className={`${styles.sms_box} `}>
                                <input
                                    type="text"
                                    inputmode="numeric"
                                    autoComplete="off"
                                    className={styles.input}
                                    ref={ref}
                                    maxLength={CODE_MAX}
                                    onChange={e => {
                                        e.target.value = e.target.value.replace(/\D+/g, '');
                                        onChange(e.target.value)
                                    }}
                                    placeholder={i18n.t('login.otp_ph')}
                                />
                                <button type='button'
                                    disabled={otpCD > 0 || otpStatus === REQ_STATUS.LOADING}
                                    className={`${styles.otp_btn} ${otpCD > 0 ? styles.cd_timer : ''}`}
                                    onClick={e => {
                                        //if (!checkPhone(control._formValues.phone)) return;
                                        onSendCode(e);
                                    }}>
                                    {
                                        otpStatus === REQ_STATUS.LOADING ? (
                                            <CircularProgress color='inherit' size={22} thickness={5} />) : (
                                            <>
                                                {
                                                    otpCD <= 0 ? i18n.t('login.btn_otp') : otpCD + "S"
                                                }
                                            </>
                                        )
                                    }
                                </button>
                            </div>
                        </div>
                    )
                }}
            />
            <button className={styles.login_btn} onClick={checkFormOnClaim}>
                {
                    handleStatus === REQ_STATUS.LOADING ? renderLoading() : <span>{buttonText}</span>
                }
                {children}
            </button>
        </form>
    )
}

export default PhoneSMS;
