import React, { useEffect, useState } from "react";
import Link from "next/link";
import MobileMenu from "../components/header/MobileMenu";
import DefaulHeader2 from "../components/header/DefaulHeader2";
import { useForm } from "react-hook-form";
import { useRouter } from "next/router";
import { useResetPassword } from "../utils/hooks";
import Swal from "sweetalert2";
import UseFullScreenLoader from "../hooks/UseFullScreenLoader";
import PasswordInput from "../components/login/PasswordInput";

const ResetPassword = () => {
  const [getLoading, setLoading] = useState<boolean>(false);
  const router = useRouter();
  const { token } = router.query;
  const {
    register,
    handleSubmit,
    reset,
    watch,
    formState: { errors },
  } = useForm();

  const password = watch("password");

  const handleChangePassword = async (changePasswordData: any) => {
    try {
      setLoading(true);
      const resetPassword = (await useResetPassword(
        token! as string,
        changePasswordData.password
      )) as ResetPasswordResp;
      setLoading(false);
      if (resetPassword.resp.success && resetPassword.status == 200) {
        reset();
        const ok = await Swal.fire({
          title: "Success!",
          text: "Password Updated Successfully!",
          icon: "success",
        });
        if (ok) {
          router.push("/login");
        }
      } else {
        await Swal.fire({
          title: "Failure!",
          text: "Something went wrong!",
          icon: "error",
        });
      }
    } catch (err) {
      setLoading(false);
      await Swal.fire({
        title: "Failure!",
        text: "Something went wrong!",
        icon: "error",
      });
    }
  };

  const getPasswordStrength = (password: string) => {
    if (!password) return { label: "", color: "transparent" };

    const strongRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*#?&]).{8,}$/;
    const mediumRegex =
      /^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[A-Z])(?=.*\d))|((?=.*[a-z])(?=.*\d))).{6,}$/;

    if (strongRegex.test(password)) {
      return { label: "Strong", color: "green" };
    } else if (mediumRegex.test(password)) {
      return { label: "Medium", color: "orange" };
    } else {
      return { label: "Weak", color: "red" };
    }
  };

  return (
    <>
      {getLoading && <UseFullScreenLoader text={"Please Hang on..."} />}
      <DefaulHeader2 />
      {/* <!--End Main Header -->  */}

      <MobileMenu />
      {/* End MobileMenu */}

      <div className="login-section">
        <div
          className="image-layer"
          style={{ backgroundImage: "url(/images/background/12.jpg)" }}
        ></div>
        <div className="outer-box">
          {/* <!-- Login Form --> */}
          <div className="login-form default-form">
            <div className="form-inner">
              <h3>Change Your Password?</h3>

              <form method="post" onSubmit={handleSubmit(handleChangePassword)}>
                <div className="col-md-12 mt-2">
                  <div className="form-group">
                    <label>Enter Password</label>
                    <PasswordInput
                      name="password"
                      placeholder="Password"
                      autoComplete="password"
                      register={register}
                      settings={{
                        required: "Password is required.",
                        minLength: {
                          value: 8,
                          message: "Password should be at least 8 characters.",
                        },
                        pattern: {
                          value:
                            /^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,}$/,
                          message:
                            "Password must contain at least one number, one uppercase letter, one lowercase letter, and one special character",
                        },
                      }}
                    />
                    {password && (
                      <p>
                        Password Strength:{" "}
                        <span
                          style={{
                            color: getPasswordStrength(password).color,
                          }}
                        >
                          {getPasswordStrength(password).label}
                        </span>
                      </p>
                    )}

                    {/* displaying validation error messages for password */}
                    {errors && errors.password && (
                      <p className="text-danger">
                        {errors.password.message as string}
                      </p>
                    )}
                  </div>
                </div>
                <div className="col-md-12 mt-2">
                  <div className="form-group">
                    <label>Confirm New Password</label>
                    <PasswordInput
                      name="confirmPassword"
                      placeholder="Confirm Your Password"
                      autoComplete="password"
                      register={register}
                      settings={{
                        required: "Confirm Password is required.",
                        validate: (value: string) =>
                          value === password || "Passwords do not match",
                      }}
                    />

                    {/* displaying validation error messages for password */}
                    {errors && errors.confirmPassword && (
                      <p className="text-danger">
                        {errors.confirmPassword.message as string}
                      </p>
                    )}
                  </div>
                </div>
                <div className="col-md-12 mt-4">
                  <div className="form-group d-flex justify-content-end align-items-center">
                    <button
                      className="theme-btn btn-style-one  mb-0"
                      type="submit"
                    >
                      Submit
                    </button>
                  </div>
                </div>
                {/* login */}
              </form>
              <div className="bottom-box">
                <div className="text">
                  Password remembered?{" "}
                  <Link href="/login" className="call-modal login">
                    Login
                  </Link>
                </div>
              </div>
              {/* End bottom-box LoginWithSocial */}
            </div>
          </div>
          {/* <!--End Login Form --> */}
        </div>
      </div>
      {/* <!-- End Info Section --> */}
    </>
  );
};

export default ResetPassword;
