import React, { useState } 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";
import { getUserDetailsByIdAPI } from "Src/services/userService";

let sdk = new MkdSDK();

const MemberLoginPage = () => {
  const schema = yup
    .object({
      email: yup.string().email().required(),
      password: yup.string().required(),
    })
    .required();
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);

  const projectParam = searchParams.get("project");

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

  const [submitLoading, setSubmitLoading] = useState(false);

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

  const SubscriptionType = localStorage.getItem("UserSubscription");

  React.useEffect(() => {
    const userId = localStorage.getItem("user");

    if (userId) {
      (async function () {
        try {
          const result = await getUserDetailsByIdAPI(userId);

          if (!result?.error) {
            localStorage.setItem("photo", result?.model?.photo);
            localStorage.setItem(
              "UserSubscription",
              result?.model?.subscription
            );
          }
        } catch (error) {}
      })();
    }
  }, []);

  const onSubmit = async (data) => {
    try {
      setSubmitLoading(true);
      const result = await sdk.login(data.email, data.password, "member");
      if (!result.error) {
        localStorage.setItem("UserSubscription", result?.subscription);
        localStorage.setItem("member_photo", result?.company_logo);

        localStorage.setItem("license_logo", result?.license_company_logo);
        dispatch({
          type: "LOGIN",
          payload: result,
        });
        localStorage.removeItem("memberTypeViewEdits");
        localStorage.removeItem("memberCompletedViewEdits");
        localStorage.removeItem("memberPendingViewEdits");

        showToast(GlobalDispatch, "Successfully Logged In", 4000, "success");
        console.log(result);

        if (projectParam) {
          localStorage.setItem("projectClientId", "");
          localStorage.setItem("projectTeamName", "");
          localStorage.setItem("projectMixTypeId", "");
          localStorage.setItem("projectMixDateStart", "");
          localStorage.setItem("projectMixDateEnd", "");
          localStorage.setItem("projectPageSize", "");
          navigate(`/member/view-project/${projectParam}`);
        }
        if (result?.plan_id) {
          localStorage.setItem("is_plan", true);
        }
        //  else if (!result?.plan_id) {
        //   localStorage.setItem("is_plan", false);
        //   navigate("/member/onboarding");
        // }
        else {
          navigate(
            redirect_uri ??
              `${
                parseInt(SubscriptionType) === 2
                  ? "/member/projects"
                  : "/member/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 */}
          <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="2xl:px-20">
                Welcome back! Please sign in to access your account.
              </p>

              <span className="mt-15 inline-block">
                {/* You can add your login illustration SVG here */}
              </span>
            </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">
                Sign In to Your Account
              </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="/member/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 MemberLoginPage;
