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

const VerifyPassword = () => {
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [msgError, setMsgError] = useState("");
  const [linkLoader, setLinkLoader] = useState(false);
  const [linkSuccess, setLinkSuccess] = useState(true);
  const [showPassword, setShowPassword] = useState(false);
  const navigate = useNavigate();
  const location = useLocation();
  const queryParams = new URLSearchParams(location?.search);
  const token = queryParams.get("passlink");
  const userApi = new usersService();

  // To Show and Hide Password
  const togglePasswordVisibility = () => {
    setShowPassword(!showPassword);
  };

  // little checker for the validity of the token
  if (token?.length != 64) {
    setLinkSuccess(false);
  }

  // Password
  const handlePassword = (e) => {
    let { name, value } = e?.target;
    if (name == "password") setPassword(value);
    if (name == "confirm_password") setConfirmPassword(value);
  };

  const completeReset = async () => {
    try {
      if (password !== "" && confirmPassword !== "") {
        if (password === confirmPassword) {
          setLinkLoader(true);
          var reqData = {
            sessionid: "DUMMY-CANNOT_BE_EMPTY",
            reset_link: token,
            newpass: password,
            step: 300,
            action: 730,
          };

          const res = await userApi?.CompleteResetPassword(reqData);

          if (res.status === 200) {
            const { data } = res;

            if (data?.status > 0 && data?.email) {
              setTimeout(() => {
                navigate("/login", { replace: true });
                setLinkLoader(false);
              }, 2000);
            } else if (data && data?.status == "Invalid Request") {
              setLinkLoader(false);
              setLinkSuccess(false);
            } else {
              setLinkLoader(false);
              setMsgError("An error occurred");
            }
          } else {
            setLinkLoader(false);
            setLinkSuccess(false);
          }
        } else {
          setLinkLoader(false);
          setMsgError("Passwords does not match");
        }
      } else {
        setMsgError("Please fill in fields");
      }
    } catch (error) {
      setLinkLoader(false);
      setLinkSuccess(false);
      throw new Error(error);
    } finally {
      setTimeout(() => {
        setMsgError(null);
      }, process.env.REACT_APP_SIGNUP_ERROR_TIMEOUT);
    }
  };

  return (
    <>
      <AuthLayout slogan="Welcome to WrenchBoard">
        <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 ? "Password Reset" : "Invalid verification link"}
                </h1>
                {linkSuccess && (
                  <span className="text-gray-400 font-medium text-[16.25px] leading-[24.375px]">
                    Enter a new password to reset
                  </span>
                )}
                {linkSuccess && (
                  <span className="text-gray-400 font-medium text-[16.25px] leading-[24.375px]">
                    We'll send an email to confirm reset
                  </span>
                )}
              </div>
              {/* If the verification was a success */}
              {linkSuccess ? (
                <SuccessfulComponent
                  password={password}
                  confirmPassword={confirmPassword}
                  handlePassword={handlePassword}
                  onSubmit={completeReset}
                  msgErr={msgError}
                  loader={linkLoader}
                  showPassword={showPassword}
                  onClick={togglePasswordVisibility}
                  navigateHandler={() => navigate("/login")}
                />
              ) : (
                <ErrorComponent onClick={() => navigate("/login")} />
              )}
            </div>
          </div>
        </div>
      </AuthLayout>
    </>
  );
};

export default VerifyPassword;

const SuccessfulComponent = ({
  onSubmit,
  navigateHandler,
  showPassword,
  onClick,
  password,
  confirmPassword,
  handlePassword,
  msgErr,
  loader,
}) => (
  <div className="input-area">
    {/* INPUT */}
    <div className="mb-5">
      <InputCom
        fieldClass="px-6"
        value={password}
        inputHandler={handlePassword}
        placeholder="● ● ● ● ● ●"
        label="Password"
        name="password"
        type={showPassword ? "text" : "password"}
        onClick={onClick}
        passIcon={showPassword ? "show-password" : "hide-password"}
      />
    </div>
    <div className="mb-5">
      <InputCom
        fieldClass="px-6"
        value={confirmPassword}
        inputHandler={handlePassword}
        placeholder="● ● ● ● ● ●"
        label="Confirm Password"
        name="confirm_password"
        type="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 className="signin-area mb-3.5">
      <button
        onClick={navigateHandler}
        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] btn-login`}
      >
        <span>Return Home</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 used this link or the link
        has broken/expired. Start with the reset process again. If it doesn't
        work, 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>
);
