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

const AdminResetPage = () => {
  const { dispatch } = React.useContext(AuthContext);
  const { dispatch: globalDispatch, state } = React.useContext(GlobalContext);
  const [submitLoading, setSubmitLoading] = useState(false);
  const search = window.location.search;
  const params = new URLSearchParams(search);
  const token = params.get("token");

  const schema = yup
    .object({
      code: yup.string().required(),
      password: yup.string().required(),
      confirmPassword: yup
        .string()
        .oneOf([yup.ref("password"), null], "Passwords must match"),
    })
    .required();

  const navigate = useNavigate();

  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.reset(token, data.code, data.password);
      if (!result.error) {
        showToast(globalDispatch, "Password Reset Successfully", 5000);
        setTimeout(() => {
          navigate(`/admin/login`);
        }, 2000);
      } 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("code", {
        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 bg-boxdark p-4 text-white md:p-8">
      <div className="shadow-default w-full rounded border-0 border-y-0 border-form-strokedark bg-boxdark text-white dark:border-form-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-[140px] dark:hidden"
                  alt="Logo"
                />
              </Link>

              <p className="2xl:px-20">
                Reset your password to regain access to your admin account.
              </p>
            </div>
          </div>

          {/* Right Side - Reset Form */}
          <div className="w-full border-form-strokedark 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">
                Admin Reset Password
              </h2>

              <form onSubmit={handleSubmit(onSubmit)}>
                <div className="mb-4">
                  <label className="mb-2.5 block font-medium text-white">
                    Code
                  </label>
                  <div className="relative">
                    <input
                      type="text"
                      placeholder="Enter code sent to your email"
                      {...register("code")}
                      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.code?.message
                          ? "border-red-500"
                          : "border-form-strokedark"
                      }`}
                    />
                    {errors.code?.message && (
                      <p className="mt-1 text-sm text-red-500">
                        {errors.code.message}
                      </p>
                    )}
                  </div>
                </div>

                <div className="mb-4">
                  <label className="mb-2.5 block font-medium text-white">
                    Password
                  </label>
                  <div className="relative">
                    <input
                      type="password"
                      placeholder="Create new password"
                      {...register("password")}
                      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.password?.message
                          ? "border-red-500"
                          : "border-form-strokedark"
                      }`}
                    />
                    {errors.password?.message && (
                      <p className="mt-1 text-sm text-red-500">
                        {errors.password.message}
                      </p>
                    )}
                  </div>
                </div>

                <div className="mb-6">
                  <label className="mb-2.5 block font-medium text-white">
                    Confirm Password
                  </label>
                  <div className="relative">
                    <input
                      type="password"
                      placeholder="Confirm your password"
                      {...register("confirmPassword")}
                      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.confirmPassword?.message
                          ? "border-red-500"
                          : "border-form-strokedark"
                      }`}
                    />
                    {errors.confirmPassword?.message && (
                      <p className="mt-1 text-sm text-red-500">
                        {errors.confirmPassword.message}
                      </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" />
                    ) : (
                      "Reset Password"
                    )}
                  </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 AdminResetPage;
