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

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, admin);

      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);
      console.log("Error", error);
      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="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="email"
            >
              Email
            </label>
            <input
              type="email"
              placeholder="Email"
              {...register("email")}
              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 && 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 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}
            >
              Forgot 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 AdminForgotPage;
