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, useLocation } from "react-router-dom";
import { GlobalContext, showToast } from "../globalContext";
import { AuthContext, tokenExpireError } from "../authContext";
import { ClipLoader } from "react-spinners";

const SUCCESS_MSG = "Reset code sent to your email";

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

  const [submitLoading, setSubmitLoading] = useState(false);
  const [showSuccessMsg, setShowSuccessMsg] = useState(false);
  const location = useLocation();

  let trimmedUrl = location.pathname.slice(1);
  let extractedPart = trimmedUrl.split("/")[0];

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

  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.forgot(extractedPart, data.email);

      if (!result.error) {
        setShowSuccessMsg(true);
        showToast(globalDispatch, SUCCESS_MSG);
      } 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);
      showToast(globalDispatch, error.message, 4000, "error");
      setError("email", {
        type: "manual",
        message: error.response.data.message
          ? error.response.data.message
          : error.message,
      });
      tokenExpireError(
        globalDispatch,
        error.response.data.message
          ? error.response.data.message
          : error.message
      );
    }
  };

  return (
    <div className="flex min-h-screen w-full items-center justify-center bg-boxdark p-4 text-white md:p-8">
      <div className="shadow-default w-full rounded border-0 border-y-0 border-stroke bg-boxdark text-white dark:border-strokedark dark:bg-boxdark">
        <div className="flex flex-wrap items-center">
          {/* Left Side - Image */}
          <div className="hidden w-full xl:block xl:w-1/2">
            <div className="px-26 py-17.5 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-[350px] dark:hidden"
                  alt="Logo"
                />
              </Link>

              <p className="2xl:px-20">
                Enter your email to receive password reset instructions.
              </p>
            </div>
          </div>

          {/* Right Side - Forgot Form */}
          <div className="w-full border-strokedark xl:w-1/2 xl:border-l-2 dark:border-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">
                Admin Forgot Password
              </h2>

              <form onSubmit={handleSubmit(onSubmit)}>
                <div className="mb-4">
                  <label className="mb-2.5 block font-medium 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 outline-none focus:border-primary focus-visible:shadow-none dark:border-form-strokedark dark:bg-form-input ${
                        errors.email?.message
                          ? "border-red-500"
                          : "border-strokedark"
                      }`}
                    />
                    {errors.email?.message && (
                      <p className="mt-1 text-sm text-red-500">
                        {errors.email.message}
                      </p>
                    )}
                    {showSuccessMsg && (
                      <p className="mt-1 text-sm text-green-500">
                        {SUCCESS_MSG}
                      </p>
                    )}
                  </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="white" />
                    ) : (
                      "Send Reset Link"
                    )}
                  </button>
                </div>

                <div className="mt-6 text-center">
                  <Link to="/admin/login" className="text-primary">
                    Back to Login
                  </Link>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default AdminForgotPage;
