import { useState, useLayoutEffect, useCallback } from "react";
import { useLocation, Link, useNavigate } from "react-router-dom";
import AuthLayout from "../AuthLayout";
import InputCom from "../../Helpers/Inputs/InputCom";
import usersService from "../../../services/UsersService";
import WrenchBoard from "../../../assets/images/wrenchboard.png";
import debounce from "../../../hooks/debounce";

export default function VerifyLink() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [msgError, setMsgError] = useState("");
  const [linkLoader, setLinkLoader] = useState(false);
  const [pageLoader, setPageLoader] = useState(true);
  const [linkSuccess, setLinkSuccess] = useState(true);
  const navigate = useNavigate();
  const location = useLocation();
  const queryParams = new URLSearchParams(location?.search);
  const token = queryParams.get("vlnk");
  const userApi = new usersService();

  // email
  const handleEmail = (e) => {
    setEmail(e.target.value);
  };
  // password
  const handlePassword = (e) => {
    setPassword(e.target.value);
  };

  // for verifying the incoming verification link and render the correct component
  const verifyEmail = useCallback(async (code) => {
    try {
      const verifyRes = await userApi.verifyEmail(code);
      if (verifyRes.status === 200) {
        let { data } = verifyRes;

        if (
          data &&
          data.internal_return >= 0 &&
          data.status_text === "Link Verfied"
        ) {
          setPageLoader(false);
        } else {
          setPageLoader(false);
          setLinkSuccess(false);
        }
      }
    } catch (error) {
      setPageLoader(false);
      setLinkSuccess(false);
      throw new Error(error);
    }
  }, []);

  // delay verify requests by 10000ms
  const debouncedEmail = debounce(verifyEmail, 1000);

  // if verification is okay. set a complete signup form
  const completeSignup = async () => {
    if (email === "" && password === "") {
      setMsgError("Please fill in fields");
    }

    try {
      if (email !== "" && password !== "") {
        setLinkLoader(true);
        var postData = {
          username: email,
          password: password,
          login_mode: 100,
          sessionid: "STARTER-NOTREAL",
          verify_link: token,
          action: 11012,
        };
        const res = await userApi.CompleteSignUp(postData);

        if (res.status === 200) {
          const { data } = res;
          if (
            data?.status > 0 &&
            data?.internal_return == 100 &&
            data?.session != ""
          ) {
            localStorage.setItem("email", `${data?.email}`);
            localStorage.setItem("member_id", `${data?.member_id}`);
            localStorage.setItem("session_token", `${data?.session}`);
            localStorage.setItem("added", `${data?.added}`);
            localStorage.setItem("city", `${data?.city}`);
            localStorage.setItem("country", `${data?.country}`);
            localStorage.setItem("firstname", `${data?.firstname}`);
            localStorage.setItem("last_login", `${data?.last_login}`);
            localStorage.setItem("lastname", `${data?.lastname}`);
            localStorage.setItem("state", `${data?.state}`);
            localStorage.setItem("zip_code", `${data?.zip_code}`);
            localStorage.setItem("session", `${data?.session}`);

            navigate("/", { replace: true });
            setLinkLoader(false);
          } else {
            setLinkLoader(false);
            setMsgError("Invalid Link or Password Combination");
          }
        } else {
          setLinkLoader(false);
          setLinkSuccess(false)
          setMsgError("An error occurred");
        }
      }
    } catch (error) {
      setLinkLoader(false);
      setLinkSuccess(false)
      throw new Error(error);
    } finally {
      setTimeout(() => {
        setMsgError(null);
      }, process.env.REACT_APP_SIGNUP_ERROR_TIMEOUT);
    }
  };

  useLayoutEffect(() => {
    debouncedEmail(token);
  });

  return (
    <>
      <AuthLayout slogan="Welcome to WrenchBoard">
        {pageLoader ? (
          <img src={WrenchBoard} alt="wrenchboard" className="h-10 mx-auto" />
        ) : (
          <div className="w-full">
            <div className="mb-12">
              <Link to="#">
                <img
                  src={WrenchBoard}
                  alt="wrenchboard"
                  className="h-10 mx-auto"
                />
              </Link>
            </div>
            <div className="content-wrapper login shadow-md w-full lg:max-w-[500px] mx-auto flex justify-center items-center dark:bg-dark-white 2xl:w-[828px] rounded-[0.475rem] sm:p-7 p-5">
              <div className="w-full">
                <div className="title-area flex flex-col justify-center items-center relative text-center mb-7">
                  <h1 className="text-[#181c32] font-semibold dark:text-white mb-3 leading-[27.3px] text-[22.75px]">
                    {linkSuccess
                      ? "Sign In to WrenchBoard"
                      : "Invalid verification link"}
                  </h1>
                </div>
                {/* If the verification was a success */}
                {linkSuccess ? (
                  <SuccessfulComponent
                    email={email}
                    password={password}
                    handleEmail={handleEmail}
                    handlePassword={handlePassword}
                    onSubmit={completeSignup}
                    msgErr={msgError}
                    loader={linkLoader}
                  />
                ) : (
                  <ErrorComponent onClick={() => navigate("/login")} />
                )}
              </div>
            </div>
          </div>
        )}
      </AuthLayout>
    </>
  );
}

const SuccessfulComponent = ({
  onSubmit,
  password,
  handlePassword,
  email,
  handleEmail,
  msgErr,
  loader,
}) => (
  <div className="input-area">
    {/* INPUT */}
    <div className="mb-5">
      <InputCom
        value={email}
        inputHandler={handleEmail}
        placeholder="support@mermsemr.com"
        label="Email"
        name="email"
        type="email"
        iconName="message"
      />
    </div>
    <div className="mb-5">
      <InputCom
        value={password}
        inputHandler={handlePassword}
        placeholder="● ● ● ● ● ●"
        label="Password"
        name="password"
        type="password"
        iconName="password"
      />
    </div>
    {msgErr && (
      <div className="relative p-4 text-[#912741] bg-[#fcd9e2] border-[#fbc6d3] mb-4 rounded-[0.475rem] text-md font-light leading-[19.5px] text-[13px]">
        {msgErr}
      </div>
    )}
    <div className="signin-area mb-3.5">
      <button
        onClick={onSubmit}
        type="button"
        className={`btn-login  rounded-[0.475rem] mb-6 text-xl text-white flex justify-center bg-[#4687ba] hover:bg-[#009ef7] transition-all duration-300 items-center text-[15px]`}
      >
        {loader ? (
          <div className="signup btn-loader"></div>
        ) : (
          <span>Continue</span>
        )}
      </button>
    </div>
  </div>
);

const ErrorComponent = ({ onClick }) => (
  <div className="input-area">
    <div className="my-5">
      <p className="text-[14px] leading-[19px] text-center text-[#181c32]">
        This error occurs because you have already verified this link or the
        link has expired. Try login or reset password. If none worked, try to
        create the account from the start.
      </p>
    </div>

    <div className="signin-area flex justify-center mb-3.5">
      <button
        onClick={onClick}
        type="button"
        className={`rounded-[0.475rem] mb-6 text-[15px] font-semibold text-[#009ef7] hover:text-white flex justify-center bg-[#f1faff] hover:bg-[#009ef7] transition-all duration-300 items-center py-[0.8875rem] px-[1.81rem]`}
      >
        <span>Return Home</span>
      </button>
    </div>
  </div>
);
