import React, { useState } from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import MkdSDK from "Utils/MkdSDK";
import { Link } from "react-router-dom";
import { useNavigate } from "react-router-dom";
import { AuthContext, tokenExpireError } from "Src/authContext";
import { showToast } from "Context/Global";
import { InteractiveButton } from "Components/InteractiveButton";

const AdminResetPage = () => {
  const { dispatch } = React.useContext(AuthContext);
  const [submitLoading, setSubmitLoading] = useState(false);
  const search = window.location.search;
  const params = new URLSearchParams(search);
  const token = params.get("token");

  const schema = yup
    .object({
      code: yup.string().required(),
      password: yup.string().required(),
      confirmPassword: yup
        .string()
        .oneOf([yup.ref("password"), null], "Passwords must match"),
    })
    .required();

  const navigate = useNavigate();

  const {
    register,
    handleSubmit,
    setError,
    formState: { errors },
  } = useForm({
    resolver: yupResolver(schema),
  });

  const onSubmit = async (data) => {
    let sdk = new MkdSDK();
    try {
      setSubmitLoading(true);
      const result = await sdk.reset(token, data.code, data.password);
      if (!result.error) {
        showToast(dispatch, "Password Reset");
        setTimeout(() => {
          navigate(`/admin/login`);
        }, 2000);
      } else {
        if (result.validation) {
          const keys = Object.keys(result.validation);
          for (let i = 0; i < keys.length; i++) {
            const field = keys[i];
            setError(field, {
              type: "manual",
              message: result.validation[field],
            });
          }
        }
      }
      setSubmitLoading(false);
    } catch (error) {
      setSubmitLoading(false);
      console.log("Error", error);
      setError("code", {
        type: "manual",
        message: error?.response?.data?.message
          ? error?.response?.data?.message
          : error?.message,
      });
      tokenExpireError(
        dispatch,
        error?.response?.data?.message
          ? error?.response?.data?.message
          : error?.message
      );
    }
  };

  return (
    <div className="flex min-h-screen w-full items-center justify-center">
      <div className="mx-auto w-full max-w-xs">
        <form
          onSubmit={handleSubmit(onSubmit)}
          className="mb-4 mt-8 rounded bg-[#FFF4EC] px-8 pb-8 pt-6 shadow-md "
        >
          <div className="mb-4">
            <label
              className="mb-2 block text-sm font-bold text-gray-700"
              htmlFor="code"
            >
              Code
            </label>
            <input
              type="text"
              placeholder="Enter code sent to your email"
              {...register("code")}
              className={`"shadow focus:shadow-outline w-[100px] appearance-none rounded border border-[#1f1d1a] bg-transparent px-3 py-2 leading-tight text-[#1d1f1a] focus:outline-none   sm:w-[180px] ${
                errors.code?.message ? "border-red-500" : ""
              }`}
            />
            <p className="text-xs italic text-red-500">
              {errors.code?.message}
            </p>
          </div>
          <div className="mb-6">
            <label
              className="mb-2 block text-sm font-bold text-gray-700"
              htmlFor="password"
            >
              Password
            </label>
            <input
              type="password"
              placeholder="******************"
              {...register("password")}
              className={`focus:shadow-outline mb-3 w-full  appearance-none rounded border border-[#1f1d1a] px-3 py-2 leading-tight text-gray-700   shadow focus:outline-none ${
                errors.password?.message ? "border-red-500" : ""
              }`}
            />
            <p className="text-xs italic text-red-500">
              {errors.password?.message}
            </p>
          </div>
          <div className="mb-6">
            <label
              className="mb-2 block text-sm font-bold text-gray-700"
              htmlFor="confirmPassword"
            >
              Confirm Password
            </label>
            <input
              type="password"
              placeholder="******************"
              {...register("confirmPassword")}
              className={`focus:shadow-outline mb-3 w-full  appearance-none rounded border border-[#1f1d1a] px-3 py-2 leading-tight text-gray-700   shadow focus:outline-none ${
                errors.confirmPassword?.message ? "border-red-500" : ""
              }`}
            />
            <p className="text-xs italic text-red-500">
              {errors.confirmPassword?.message}
            </p>
          </div>
          <div className="flex items-center justify-between">
            <InteractiveButton
              className="focus:shadow-outline bg-primary-black rounded px-4 py-2 font-bold text-white focus:outline-none disabled:cursor-not-allowed"
              type="submit"
              loading={submitLoading}
              disabled={submitLoading}
            >
              Reset Password
            </InteractiveButton>
            <Link
              className="text-primary-black inline-block align-baseline text-sm font-bold"
              to="/admin/login"
            >
              Login?
            </Link>
          </div>
        </form>
        <p className="text-center text-xs text-gray-500">
          &copy; {new Date().getFullYear()} manaknightdigital inc. All rights
          reserved.
        </p>
      </div>
    </div>
  );
};

export default AdminResetPage;
