import InputText from "../../utils/inputText";
import OverlayBox from "../../utils/others/overlayBox";
import style from "./forgetPassword.module.css";
import { Email } from "@mui/icons-material";
import { useDispatch, useSelector } from "react-redux";
import { accountStoreActions } from "@/store/account";
import { authApi } from "@/api/api";
import { useCallback, useRef, useState } from "react";
import ReCAPTCHA from "react-google-recaptcha";
import { useEmailValidation } from "@/customHook/useValidation";
import Loader from "@/components/utils/loader";
import { GoogleReCaptcha } from "react-google-recaptcha-v3";

const ForgetPassword = (props) => {
  const fpOpen = useSelector((state) => state.accountStore.forgetPasswordUI);
  const dispatch = useDispatch();
  const [error, setError] = useState("");
  const [refreshReCaptcha, setRefreshReCaptcha] = useState(false);
  const [captcha, setCaptcha] = useState();
  const [fpData, setFPData] = useState({
    email: "",
  });
  const emailValidation = useEmailValidation(fpData.email);
  const [fpError, setFPError] = useState({
    email: false,
  });
  const [fpWarn, setFPWarn] = useState(null);
  const [fpLoader, setfpLoader] = useState(false);

  const onVerify = useCallback((token) => {
    setCaptcha(token);
  }, []);

  const forgetPasswordSubmitHandler = async (e) => {
    e.preventDefault();
    if (!captcha) {
      setError("Complete Captcha!");
      return 0;
    }
    setFPWarn(null);
    setfpLoader(true);
    console.log("fpData, ", fpData);
    let errorFound = false;
    if (!emailValidation.value) {
      setFPError((prev) => {
        let errorObject = { ...prev };
        errorObject.email = true;
        return errorObject;
      });
      errorFound = true;
    } else {
      setFPError((prev) => {
        let errorObject = { ...prev };
        errorObject.email = false;
        return errorObject;
      });
    }

    if (errorFound === false) {
      await authApi
        .post("/customer/request/reset", {
          ...fpData,
          token: captcha,
        })
        .then((res) => {
          console.log(":res.status ", res.status);
          if (res.data.success === true) {
            dispatch(accountStoreActions.closeForgetPasswordUI());
            props.setFPSuccessOpen(true);
          } else {
            setError("Password Reset Failed!!!");
            setRefreshReCaptcha((prev) => !prev);
          }
          setfpLoader(false);
        })
        .catch((err) => {
          console.log("err: ", err);
          if (err.response.data.error === "No User Exist") {
            setError("No User Exist");
          } else {
            setError("Password Reset Failed!!!");
          }
          setRefreshReCaptcha((prev) => !prev);
          setfpLoader(false);
        });
    } else {
      setfpLoader(false);
    }
  };

  return (
    <OverlayBox
      open={fpOpen}
      close={(value) => {
        setfpLoader(false);
        dispatch(accountStoreActions.closeForgetPasswordUI());
        setError();
      }}
      title="Forget Password"
      head={true}
      blur={true}
      customClass={style.customOverlayClass}
    >
      <div className={style.fp_form}>
        <div className={style.section_box}>
          <form onSubmit={forgetPasswordSubmitHandler}>
            <div className={style.input_section}>
              <InputText
                type="email"
                name="email"
                icon={<Email />}
                placeholder="Email"
                getValue={(value) => {
                  setFPData({ email: value });
                }}
                required={true}
                label={"Email"}
                customClass={style.customInputClass}
              />
              <center>
                <GoogleReCaptcha
                  onVerify={onVerify}
                  refreshReCaptcha={refreshReCaptcha}
                />
              </center>
              <div className={style.status}>
                {error && (
                  <div className={`${style.error_status}`}>{error}</div>
                )}
              </div>
              <button
                type="submit"
                className={`teritary_btn ${style.button} mt-2`}
                disabled={fpLoader ? true : false}
              >
                {fpLoader ? <Loader className={style.loader} /> : "Submit"}
              </button>
            </div>
          </form>
        </div>
      </div>
    </OverlayBox>
  );
};

export default ForgetPassword;
