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 { InteractiveButton } from "@/components/InteractiveButton";
import { GlobalContext, showToast } from "@/context/Global";
import { tokenExpireError } from "@/context/Auth";

const AdminForgotPage = () => {
  const [submitLoading, setSubmitLoading] = useState(false);

  const schema = yup
    .object({
      email: yup.string().email().required(),
    })
    .required();

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

  const { dispatch } = React.useContext(GlobalContext);

  const onSubmit = async (data) => {
    let sdk = new MkdSDK();
    try {
      setSubmitLoading(true);
      const result = await sdk.forgot(data.email);

      if (!result.error) {
        showToast(dispatch, "Reset Code Sent");
      } 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);
      setError("email", {
        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="mx-auto w-full max-w-xs">
        <form
          onSubmit={handleSubmit(onSubmit)}
          className="mb-4 mt-8 rounded bg-white 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="email"
            >
              Email
            </label>
            <input
              type="email"
              placeholder="Email"
              {...register("email")}
              className={`"shadow focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 focus:outline-none ${errors && errors.email?.message ? "border-red-500" : ""
                }`}
            />
            <p className="text-xs italic text-red-500">
              {errors && errors.email?.message}
            </p>
          </div>

          <div className="flex items-center justify-between">
            <InteractiveButton
              className="focus:shadow-outline rounded bg-primaryBlue px-4 py-2 font-bold text-white focus:outline-none disabled:cursor-not-allowed"
              type="submit"
              loading={submitLoading}
              disabled={submitLoading}
            >
              Forgot Password
            </InteractiveButton>
            <Link
              className="inline-block align-baseline text-sm font-bold text-primaryBlue"
              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>
    </>
  );
};

export default AdminForgotPage;
