import InputText from "../../utils/inputText";
import OverlayBox from "../../utils/others/overlayBox";
import style from "./signIn.module.css";
import { Email, Key } from "@mui/icons-material";
import { useDispatch, useSelector } from "react-redux";
import { accountStoreActions } from "@/store/account";
import { authApi, customerApi, managerApi } from "@/api/api";
import Loader from "@/components/utils/loader";
import { useCallback, useEffect, useRef, useState } from "react";
import jwtDecode from "jwt-decode";
import ReCAPTCHA from "react-google-recaptcha";
import { GoogleReCaptcha } from "react-google-recaptcha-v3";
import { loadCart, loadWishlist } from "@/store/index";
import { useRouter } from "next/router";

const SignIn = (props) => {
  const signInUI = useSelector((state) => state.accountStore.signInUI);
  const dispatch = useDispatch();
  const [loader, setLoader] = useState(false);
  const [error, setError] = useState("");
  const [captcha, setCaptcha] = useState();
  const [emailNotVerified, setEmailNotVerified] = useState(false);
  const [refreshReCaptcha, setRefreshReCaptcha] = useState(false);
  const router = useRouter();

  useEffect(() => {
    console.log("router: ", router.pathname);
  }, []);
  const onSignIn = async (e) => {
    try {
      e.preventDefault();
      if (!captcha) {
        setError("Complete Captcha!");
        return 0;
      }
      if (loader) return;
      setError("");
      setLoader(true);
      console.log("captcha1234", captcha);
      const response = await authApi.post(
        "/customer/login",
        {
          email: e.target.elements.email.value,
          password: e.target.elements.password.value,
          token: captcha,
        },
        { withCredentials: true }
      );
      if (response.data.success) {
        const tokenData = response.data.accessToken;
        console.log("response.data.accessToken;", response.data.accessToken);
        if (response.data.success === true) {
          await customerApi.post(
            "/clear-cart-data",
            {},
            {
              withCredentials: true,
            }
          );
          console.log("token: updated");
          await customerApi.interceptors.request.use(
            (config) => {
              if (tokenData) {
                config.headers["Authorization"] = "Bearer " + tokenData;
              }
              config.withCredentials = true;
              return config;
            },
            (error) => {
              Promise.reject(error);
            }
          );
          await authApi.interceptors.request.use(
            (config) => {
              if (tokenData) {
                config.headers["Authorization"] = "Bearer " + tokenData;
              }
              config.withCredentials = true;
              return config;
            },
            (error) => {
              Promise.reject(error);
            }
          );
          await managerApi.interceptors.request.use(
            (config) => {
              if (tokenData) {
                config.headers["Authorization"] = "Bearer " + tokenData;
              }
              config.withCredentials = true;
              return config;
            },
            (error) => {
              Promise.reject(error);
            }
          );
          loadCart("login");
          loadWishlist();
          dispatch(
            accountStoreActions.updateLoggedIn({
              loggedIn: true,
              name: response.data.name,
              image: response.data.image,
              userid: response.data._id,
            })
          );
          if (router.pathname === "/confirm/email") {
            router.push("/");
          }
          dispatch(accountStoreActions.closeSignInUI());
        } else {
          setRefreshReCaptcha((prev) => !prev);
          setError("Login Failed");
        }
      }
      setLoader(false);
    } catch (err) {
      setLoader(false);
      console.log("err: ", err);
      setRefreshReCaptcha((prev) => !prev);
      if (err.response.data.error == "Email Not Verified") {
        setEmailNotVerified(true);
        setError(err.response.data.error);
      } else setError("Login Failed");
    }
  };

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

  return (
    <OverlayBox
      open={signInUI}
      close={(value) => {
        setLoader(false);
        setError("");
        setEmailNotVerified(false);
        dispatch(accountStoreActions.closeSignInUI());
      }}
      title="Account"
      head={true}
      blur={true}
      customClass={style.customOverlayClass}
    >
      <div className={style.signIn_form}>
        <div className={style.section_box}>
          <form onSubmit={onSignIn}>
            <div className={style.input_section}>
              <InputText
                type="email"
                name="email"
                icon={<Email />}
                placeholder="Email"
                getValue={(value) => {}}
                required={true}
                label={"Email"}
                customClass={style.customInputClass}
              />
              <InputText
                type="password"
                name="password"
                icon={<Key />}
                placeholder="Password"
                label={"Password"}
                getValue={(value) => {}}
                required={true}
                customClass={style.customInputPasswordClass}
              />
              <div className={style.option}>
                <p
                  className="mb-2"
                  onClick={() => {
                    dispatch(accountStoreActions.openForgetPasswordUI());
                    dispatch(accountStoreActions.closeSignInUI());
                    setError("");
                    setEmailNotVerified(false);
                  }}
                >
                  Forget password
                </p>
                <p
                  className="mb-2"
                  onClick={() => {
                    dispatch(accountStoreActions.openSignUpUI());
                    dispatch(accountStoreActions.closeSignInUI());
                    setError("");
                    setEmailNotVerified(false);
                  }}
                >
                  Create Account
                </p>
              </div>
              <center>
                <GoogleReCaptcha
                  onVerify={onVerify}
                  refreshReCaptcha={refreshReCaptcha}
                />
              </center>
              <div className={style.status}>
                {error && (
                  <>
                    <div className={`${style.error_status}`}>{error}</div>
                    {emailNotVerified && (
                      <div
                        className={style.resentEmailBtn}
                        onClick={() => {
                          dispatch(accountStoreActions.closeSignInUI());
                          setError("");
                          setEmailNotVerified(false);
                          props.resentEmail(true);
                        }}
                      >
                        ( Click Here To Resent )
                      </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`}
                >
                  Sign In
                </button>
              )}
            </div>
          </form>
        </div>
        {/* <div className={style.signIn_divider}>
          <hr />
          OR
          <hr />
        </div>
        <div className={style.signIn_with_google}>
          <div className={style.logo}>
            <span />
          </div>
          <div className={style.text_area}>Sign In With Google</div>
        </div> */}
      </div>
    </OverlayBox>
  );
};

export default SignIn;
