import React from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { GlobalContext, showToast } from "../globalContext";
import { AuthContext } from "../authContext";
import MkdSDK from "../utils/MkdSDK";
import { ClipLoader } from "react-spinners";

let sdk = new MkdSDK();

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

  const { dispatch } = React.useContext(AuthContext);
  const { dispatch: globalDispatch, state } = React.useContext(GlobalContext);

  const [submitLoading, setSubmitLoading] = React.useState(false);
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const redirect_uri = searchParams.get("redirect_uri");
  const navigate = useNavigate();

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

  const onSubmit = async (data) => {
    try {
      setSubmitLoading(true);
      const result = await sdk.login(data.email, data.password, "admin");
      if (!result.error) {
        dispatch({
          type: "LOGIN",
          payload: result,
        });
        localStorage.removeItem("adminTypeViewEdits");
        localStorage.removeItem("adminCompletedViewEdits");
        localStorage.removeItem("adminPendingViewEdits");
        localStorage.removeItem("adminSelectedMemberId");
        showToast(globalDispatch, "Successfully Logged In", 4000, "success");
        navigate(redirect_uri ?? "/admin/dashboard");
      } else {
        setSubmitLoading(false);
        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],
            });
          }
        }
      }
    } catch (error) {
      setSubmitLoading(false);
      showToast(globalDispatch, error.message, 4000, "error");
      setError("email", {
        type: "manual",
        message: error.response.data.message
          ? error.response.data.message
          : error.message,
      });
    }
  };

  return (
    <div className="max-w-screen flex h-full">
      <div className="shadow-default flex min-h-screen w-full items-center justify-center rounded border border-form-strokedark bg-boxdark dark:border-form-strokedark dark:bg-boxdark">
        <div className="flex w-full flex-wrap items-center">
          {/* Left Side - Image and Logo */}
          <div className="hidden w-full xl:block xl:w-1/2">
            <div className="py-17.5 px-26 text-center">
              <Link className="mb-5.5 inline-block" to="/">
                <img
                  crossOrigin="anonymous"
                  src={
                    state.siteLogo ??
                    `${window.location.origin}/new/cheerEQ-2-Ed2.png`
                  }
                  className="h-auto w-[300px] dark:hidden"
                  alt="Logo"
                />
              </Link>

              <p className="text-white 2xl:px-20">
                Welcome back! Please sign in to access your admin account.
              </p>
            </div>
          </div>

          {/* Right Side - Login Form */}
          <div className="w-full border-form-strokedark px-12 xl:w-1/2 xl:border-l-2 dark:border-form-strokedark">
            <div className="sm:p-12.5 xl:p-17.5 w-full p-4">
              <h2 className="mb-9 text-2xl font-bold text-white sm:text-title-xl2 dark:text-white">
                Admin Sign In
              </h2>

              <form onSubmit={handleSubmit(onSubmit)}>
                <div className="mb-4">
                  <label className="mb-2.5 block font-medium text-white dark:text-white">
                    Email
                  </label>
                  <div className="relative">
                    <input
                      type="email"
                      placeholder="Enter your email"
                      {...register("email")}
                      className="w-full rounded-lg border border-form-strokedark bg-form-input py-4 pl-6 pr-10 text-white outline-none focus:border-primary focus-visible:shadow-none dark:border-form-strokedark dark:bg-form-input dark:text-white dark:focus:border-primary"
                    />
                    {errors.email && (
                      <span className="mt-1 text-sm text-red-500">
                        {errors.email.message}
                      </span>
                    )}
                  </div>
                </div>

                <div className="mb-6">
                  <label className="mb-2.5 block font-medium text-white dark:text-white">
                    Password
                  </label>
                  <div className="relative">
                    <input
                      type="password"
                      placeholder="Enter your password"
                      {...register("password")}
                      className="w-full rounded-lg border border-form-strokedark bg-form-input py-4 pl-6 pr-10 text-white outline-none focus:border-primary focus-visible:shadow-none dark:border-form-strokedark dark:bg-form-input dark:text-white dark:focus:border-primary"
                    />
                    {errors.password && (
                      <span className="mt-1 text-sm text-red-500">
                        {errors.password.message}
                      </span>
                    )}
                  </div>
                </div>

                <div className="mb-5">
                  <button
                    type="submit"
                    disabled={submitLoading}
                    className="w-full cursor-pointer rounded-lg border border-primary bg-primary p-4 text-white transition hover:bg-opacity-90 disabled:opacity-50"
                  >
                    {submitLoading ? (
                      <ClipLoader size={18} color="#fff" />
                    ) : (
                      "Sign In"
                    )}
                  </button>
                </div>

                <div className="mt-6 text-center">
                  <Link
                    to="/admin/forgot"
                    className="text-primary hover:underline"
                  >
                    Forgot Password?
                  </Link>
                </div>

                <div className="mt-6 text-center">
                  <Link to="/" className="text-white hover:text-primary">
                    Back to Home
                  </Link>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default AdminLoginPage;
