import React, { useCallback, useEffect, useRef, useState } from "react";
import style from "./account.module.css";
import InputText from "../../utils/inputText";
import OverlayBox from "../../utils/others/overlayBox";
import Loader from "@/components/utils/loader";
import { Email, Key, Person, Phone, ThumbUp } from "@mui/icons-material";
import { useDispatch, useSelector } from "react-redux";
import { accountStoreActions } from "@/store/account";
import { authApi, customerApi } from "@/api/api";
import {
  usePhoneValidation,
  usePasswordValidation,
  useEmailValidation,
} from "@/customHook/useValidation";
import SignIn from "./signIn";
import SignUp from "./signUp";
import ReCAPTCHA from "react-google-recaptcha";
import ForgetPassword from "./forgetPassword";
import { GoogleReCaptcha } from "react-google-recaptcha-v3";

const Account = (props) => {
  const forgetPass = useSelector(
    (state) => state.accountStore.forgetPasswordUI
  );
  const [successOpen, setSuccessOpen] = useState(false);
  const [registerSuccessOpen, setRegisterSuccessOpen] = useState(false);
  const dispatch = useDispatch();
  const [loader, setLoader] = useState(false);
  const [resentEmailUI, setResentEmailUI] = useState(false);
  const [resentEmail, setResetEmail] = useState(null);
  const [refreshReCaptcha, setRefreshReCaptcha] = useState(false);
  const [captcha, setCaptcha] = useState();
  const [error, setError] = useState(null);
  const emailValidation = useEmailValidation(resentEmail);

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

  const onResentEmail = async (e) => {
    e.preventDefault();
    if (emailValidation.value == false) {
      setError("Email Validation Failed");
      return;
    }
    if (!captcha) {
      setError("Complete Captcha!");
      return 0;
    }
    setLoader(true);
    await authApi
      .post("/customer/confirm/mail/resent", {
        email: resentEmail,
        token: captcha,
      })
      .then((res) => {
        console.log(":res.status ", res.status);
        if (res.data.success === true) {
          setResentEmailUI(false);
          setRegisterSuccessOpen(true);
        } else {
          setError("Failed To Send Email");
          setRefreshReCaptcha((prev) => !prev);
        }
        setLoader(false);
      })
      .catch((err) => {
        console.log("err: ", err);
        if (
          err.response.status === 500 &&
          err.response.data.error == "No User Exist"
        ) {
          setError("No User Exist");
        } else if (err.response.data.error == "Email Already Verified") {
          setError("Email Already Verified");
        } else {
          setError("Failed To Send Email");
        }
        setRefreshReCaptcha((prev) => !prev);
        setLoader(false);
      });
  };
  return (
    <>
      {/* Register Success Box */}
      <OverlayBox
        open={registerSuccessOpen}
        close={(value) => {
          setRegisterSuccessOpen(false);
        }}
        head={false}
        blur={true}
        customClass={style.customOverlayClass}
      >
        <div className={style.forget_pass_form}>
          <div className={style.section_box}>
            <div className={style.success_icon}>
              <ThumbUp />
            </div>
            <div className={style.message}>
              We have successfully sent you a confirmation email. Please verify
              your email to continue purchasing.
            </div>
          </div>
        </div>
      </OverlayBox>

      {/* Success Box */}
      <OverlayBox
        open={successOpen}
        close={(value) => {
          setSuccessOpen(false);
        }}
        head={false}
        blur={true}
        customClass={style.customOverlayClass}
      >
        <div className={style.forget_pass_form}>
          <div className={style.section_box}>
            <div className={style.success_icon}>
              <ThumbUp />
            </div>
            <div className={style.message}>
              We have successfully sent a mail to your account, Please click on
              the link to reset password.
            </div>
          </div>
        </div>
      </OverlayBox>

      {/* Sign In Box */}
      <SignIn resentEmail={(value) => setResentEmailUI(value)} />

      {/* Sign Up Box */}
      <SignUp
        setRegisterSuccessOpen={(value) => {
          setRegisterSuccessOpen(value);
        }}
      />

      {/* Forget Password Box */}
      <ForgetPassword
        setFPSuccessOpen={(value) => {
          setSuccessOpen(value);
        }}
      />

      {/* Resent Email */}
      <OverlayBox
        open={resentEmailUI}
        close={(value) => {
          setLoader(false);
          dispatch(accountStoreActions.closeSignInUI());
          setResentEmailUI(false);
          setError("");
        }}
        title="Resent Confirm"
        head={true}
        blur={true}
        customClass={style.customOverlayClass}
      >
        <div className={style.signIn_form}>
          <div className={style.section_box}>
            <form onSubmit={onResentEmail}>
              <div className={style.input_section}>
                <InputText
                  type="email"
                  name="email"
                  icon={<Email />}
                  placeholder="Email"
                  getValue={(value) => {
                    setResetEmail(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>
                {loader ? (
                  <button
                    type="button"
                    className={`teritary_btn ${style.button} mt-2`}
                    disabled={true}
                  >
                    <Loader className={style.loader} />
                  </button>
                ) : (
                  <button
                    type="submit"
                    className={`teritary_btn ${style.button} mt-2`}
                  >
                    Resent
                  </button>
                )}
              </div>
            </form>
          </div>
        </div>
      </OverlayBox>
    </>
  );
};

export default Account;
