import React, { useContext } 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, useParams } from "react-router-dom";
import { useNavigate } from "react-router-dom";
import { AuthContext } from "../../authContext";
import { GlobalContext, showToast } from "../../globalContext";
const UserMagicLoginPage = () => {
  const schema = yup
    .object({
      email: yup.string().email().required(),
    })
    .required();

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

  const [attemptingLogin, setAttemptingLogin] = React.useState(false);

  const params = useParams();

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

  const onSubmit = async (data) => {
    let sdk = new MkdSDK();
    try {
      setAttemptingLogin(true);
      const result = await sdk.magicLoginAttempt(data.email, params?.role);

      if (!result.error) {
        setAttemptingLogin(false);

        showToast(
          GlobalDispatch,
          "Please check your mail to complete login attempt"
        );

        // dispatch({
        //   type: "LOGIN",
        //   payload: result,
        // });
        // navigate("/user/dashboard");
      }
    } catch (error) {
      setAttemptingLogin(false);

      setError("email", {
        type: "manual",
        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={`focus:shadow-outline w-full appearance-none rounded border px-3 py-2 leading-tight text-gray-700 shadow focus:outline-none ${
              errors.email?.message ? "border-red-500" : ""
            }`}
          />
          <p className="text-xs italic text-red-500">{errors.email?.message}</p>
        </div>

        <div className="flex items-center justify-between">
          <button
            type="submit"
            className="focus:shadow-outline rounded bg-primary px-4 py-2 font-bold text-white hover:bg-primary/90 focus:outline-none"
          >
            {attemptingLogin ? "Attempting Log In..." : "Sign In"}{" "}
          </button>
        </div>
      </form>
      <p className="text-center text-xs text-gray-500">
        &copy; {new Date().getFullYear()} Equality Records. All rights reserved.
      </p>
    </div>
  );
};

export default UserMagicLoginPage;
