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 { InteractiveButton } from "Components/InteractiveButton";

const ManagerResetPage = () => {
  const { dispatch } = React.useContext(AuthContext);
  const { dispatch: globalDispatch } = 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(`/manager/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="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 */}
          <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="/new/cheerEQ-2-Ed2.png"
                  className="h-auto w-[300px] dark:hidden"
                  alt="Logo"
                />
              </Link>

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

          {/* Right Side - Reset 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">
                Reset Your Password
              </h2>

              <form onSubmit={handleSubmit(onSubmit)}>
                <div className="mb-4">
                  <label className="mb-2.5 block font-medium text-white dark: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 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.code && (
                      <span className="mt-1 text-sm text-red-500">
                        {errors.code.message}
                      </span>
                    )}
                  </div>
                </div>

                <div className="mb-4">
                  <label className="mb-2.5 block font-medium text-white dark:text-white">
                    New Password
                  </label>
                  <div className="relative">
                    <input
                      type="password"
                      placeholder="Enter new 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-6">
                  <label className="mb-2.5 block font-medium text-white dark:text-white">
                    Confirm Password
                  </label>
                  <div className="relative">
                    <input
                      type="password"
                      placeholder="Confirm new password"
                      {...register("confirmPassword")}
                      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.confirmPassword && (
                      <span className="mt-1 text-sm text-red-500">
                        {errors.confirmPassword.message}
                      </span>
                    )}
                  </div>
                </div>

                <div className="mb-5">
                  <InteractiveButton
                    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"
                    loading={submitLoading}
                  >
                    Reset Password
                  </InteractiveButton>
                </div>

                <div className="mt-6 text-center">
                  <Link
                    to="/manager/login"
                    className="text-primary hover:underline"
                  >
                    Back to Login
                  </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 ManagerResetPage;
