/* eslint-disable @typescript-eslint/no-unused-expressions */
import React, { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { Formik, Form, Field, ErrorMessage } from "formik";
import * as Yup from "yup";
import { api } from "../../Api/Api";
import Cookies from "js-cookie";
// import { loginCustomer } from "../../Api/CustomerApi";
import SingnUpModal from "./SingnUpModal";
import ForgotModal from "./ForgotModal";
import HourGlassLoader from "../Loader/Loader";
interface LoginModalProps {
  onClose: () => void;
  token: string;
  resetToken?: string;
}

const LoginModal: React.FC<LoginModalProps> = ({ onClose, token, resetToken }) => {
  const router = useRouter();
  const [isLoading, setIsLoading] = useState(false);
  const [activeTab, setActiveTab] = useState("user");
  const [isSubmitting, setSubmitting] = useState(false);
  const [modalType, setModalType] = useState("login");
  const [showPassword, setShowPassword] = useState(false);
  const initialValues = {
    username: "",
    password: "",
  };
  useEffect(() => {
    if (token || resetToken) {
      setModalType("register");
    }
  }, [token, resetToken]);
  const validationSchema = Yup.object().shape({
    username: Yup.string().required(activeTab === "staff" ? "Username is required" : "Email is required"),
    password: Yup.string().required("Password is required"),
  });
  const [errorMessge, seterrorMessage] = useState("");
  const handleLogin = async (values: typeof initialValues) => {
    try {
      setIsLoading(true);
      activeTab === "staff"
        ? api
            .post(
              "/customer/corporate/login",
              { email: values?.username, password: values?.password },
              false
            )
            .then(async function ([, response]) {
              setIsLoading(false);
              if (response?.token) {
                Cookies.set("AUTH_TOKEN", JSON.stringify(true));
                localStorage?.setItem("AUTH_TOKEN", response?.token);
                // Dispatch storage event
                window.dispatchEvent(new StorageEvent('storage', {
                  key: 'AUTH_TOKEN',
                  newValue: response?.token,
                  storageArea: localStorage
                }));
                localStorage?.setItem(
                  "USER_TYPE",
                  response?.data?.userType?.id
                );
                localStorage?.setItem("USER_ID", response?.data?.id);
                localStorage?.setItem(
                  "USER_TYPE_NAME",
                  response?.data?.userType?.name
                );
                localStorage?.setItem("USER_NAME", response?.data?.firstName);
                localStorage?.setItem("ALL_DATA", JSON.stringify(response));
                // login(response?.token, response?.data);

                router.push(`/dashboard`);
                window.location.reload();
                onClose();
                // window.location.reload();
                setSubmitting(false);
              } else {
                if (typeof response === "string") {
                  seterrorMessage(response);
                } else if (response && typeof response?.message === "string") {
                  seterrorMessage(response?.message);
                } else {
                  seterrorMessage("An error occurred.");
                }
                setSubmitting(false);
              }
            })
            .catch((err: unknown) => {
              setIsLoading(false);
              if (
                typeof err === "object" &&
                err !== null &&
                "response" in err &&
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                typeof (err as any).response === "object"
              ) {
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                const errorResponse = (err as any).response;

                setSubmitting(false);

                if (errorResponse.status === 401) {
                  if (typeof errorResponse.data === "string") {
                    seterrorMessage(errorResponse.data);
                  } else if (errorResponse.data && typeof errorResponse.data.message === "string") {
                    seterrorMessage(errorResponse.data.message);
                  } else {
                    seterrorMessage("An error occurred.");
                  }
                } else if (errorResponse.status === 422) {
                  // seterrorMessage((errorResponse.data as { message?: string })?.message);
                } else if (errorResponse.status === 500) {
                  // seterrorMessage("Server Error. Please try again later.");
                } else {
                  // seterrorMessage("An unexpected error occurred. Please try again.");
                }
              } else {
                console.error("Unknown error:", err);
                seterrorMessage("An unexpected error occurred.");
              }
            })
        : api
            .post(
              "/customer/login",
              { email: values?.username, password: values?.password },
              false
            )
            .then(async function ([, response]) {
              setIsLoading(false);
              if (response?.token) {
                Cookies.set("AUTH_TOKEN", JSON.stringify(true));
                localStorage?.setItem("AUTH_TOKEN", response?.token);
                // Dispatch storage event
                window.dispatchEvent(new StorageEvent('storage', {
                  key: 'AUTH_TOKEN',
                  newValue: response?.token,
                  storageArea: localStorage
                }));
                localStorage?.setItem(
                  "USER_TYPE",
                  response?.data?.userType?.id
                );
                localStorage?.setItem("USER_ID", response?.data?.id);
                localStorage?.setItem(
                  "USER_TYPE_NAME",
                  response?.data?.userType?.name
                );
                localStorage?.setItem("USER_NAME", response?.data?.firstName);
                localStorage?.setItem("ALL_DATA", JSON.stringify(response));
                // login(response?.token, response?.data);

                router.push(`/dashboard`);
                window.location.reload();
                onClose();
                // window.location.reload();
                setSubmitting(false);
              } else {
                if (typeof response === "string") {
                  seterrorMessage(response);
                } else if (response && typeof response?.message === "string") {
                  seterrorMessage(response?.message);
                } else {
                  seterrorMessage("An error occurred.");
                }
                setSubmitting(false);
              }
            })
            .catch((err: unknown) => {
              setSubmitting(false);
              setIsLoading(false);
              // Check if err is an AxiosError or has a response
              if (
                typeof err === "object" &&
                err !== null &&
                "response" in err &&
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                typeof (err as any).response === "object"
              ) {
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                const errorResponse = (err as any).response;
                const status = errorResponse.status;

                if (status === 401) {
                  if (typeof errorResponse.data === "string") {
                    seterrorMessage(errorResponse.data);
                  } else if (errorResponse.data && typeof errorResponse.data.message === "string") {
                    seterrorMessage(errorResponse.data.message);
                  } else {
                    seterrorMessage("An error occurred.");
                  }
                } else if (status === 422) {
                  // seterrorMessage((errorResponse.data as { message?: string })?.message);
                } else if (status === 500) {
                  // seterrorMessage("Server Error. Please try again later.");
                } else {
                  // seterrorMessage("An unexpected error occurred. Please try again.");
                }
              } else {
                console.error("Unknown error:", err);
                seterrorMessage("An unexpected error occurred.");
              }
            });
    } catch (error) {
      console.error(error);
    } finally {
      setIsLoading(false);
    }
  };

  const handleInitialRegister = (): void => {
    window.location.href = "/dashboard"; // 🔄 hard reload
  };

  return (
    <>
      <style>{`
        @media only screen and (min-device-width : 990px) and (max-device-width : 2000px) {
          #menu-main {
            max-width: 41.6667% !important;
            width: 41.6667% !important;
          }                  
        }
        .page-content.header-clear-medium {
          padding-bottom: 0;
          padding-top: 35px !important;
        }
        .tab-btn {
          cursor: pointer;
        }
        .tab-btn.active {
          background: purple;
          color: white;
        }
        .error-message {
          color: red;
          font-size: 12px;
          margin-top: 5px;
        }
      `}</style>
      {isLoading && <HourGlassLoader />}
      {modalType === "register" ? (
        <div id="page">
          <div className="page-content header-clear-medium">
            <div className="col-lg-12 mx-auto">
              <div className="card card-style">
                <div className="content" id="tab-group-2">
                  <SingnUpModal
                    isSubmitting={isSubmitting}
                    setModalType={setModalType}
                    token={token}
                    resetToken={resetToken}
                    handleInitialRegister={handleInitialRegister}
                    activeTabLogin={activeTab}
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      ) : modalType === "forgot" ? (
        <div id="page">
          <div className="page-content header-clear-medium">
            <div className="col-lg-12 mx-auto">
              <div className="card card-style">
                <div className="content" id="tab-group-2">
                  <ForgotModal
                    isSubmitting={isSubmitting}
                    setModalType={setModalType}
                  />
                </div>
              </div>
            </div>
          </div>
        </div>
      ) : (
        <div id="page">
          <div className="page-content header-clear-medium">
            <div className="col-lg-12 mx-auto">
              <div className="card card-style">
                <div className="content" id="tab-group-2">
                  <div className="tab-controls tabs-small tabs-rounded mb-4">
                    <a
                      onClick={() => setActiveTab("user")}
                      className={`tab-btn rounded-0 font-600  ${
                        activeTab === "user" ? "active" : ""
                      }`}
                    >
                      User Login
                    </a>
                    <a
                      onClick={() => setActiveTab("staff")}
                      className={`tab-btn rounded-0 font-600  ${
                        activeTab === "staff" ? "active" : ""
                      }`}
                    >
                      Corporate Login
                    </a>
                  </div>
                  <Formik
                    initialValues={initialValues}
                    validationSchema={validationSchema}
                    onSubmit={(values) => {
                      handleLogin(values);
                    }}
                  >
                    {() => (
                      <>
                        <Form>
                          {/* <p className="font-600 color-highlight mb-n1">
                            {`Let's start`}
                          </p> */}
                          <h1 className="font-30">Sign In</h1>
                          <p>
                            Enter your credentials below to sign into your
                            account.
                          </p>
                          {errorMessge && (
                            <div className="alert alert-danger">
                              {typeof errorMessge === "string"
                                ? errorMessge
                                : "An unexpected error occurred."}
                            </div>
                          )}
                          <div className="input-outer-box mb-3">
                            <div className="input-style no-borders has-icon validate-field mb-0">
                              <i className="fa fa-user" />
                              <Field
                                type="text"
                                name="username"
                                className="form-control font-1rem"                                
                                placeholder={activeTab === 'staff' ? 'Username' : "Email"}
                              />
                              <label className="color-highlight">
                                Username
                              </label>
                              <em>(required)</em>
                            </div>
                            <ErrorMessage
                              name="username"
                              component="div"
                              className="error-message"
                            />
                          </div>
                          <div className="input-outer-box mb-3">
                            <div className="input-style no-borders has-icon validate-field mb-0">
                              <i className="fa fa-lock" />
                              <Field
                                type={showPassword ? "text" : "password"}
                                name="password"
                                className="form-control"
                                placeholder="Password"
                              />
                              <label className="color-highlight">
                                Password
                              </label>
                              <em>(required)</em>

                              <i
                                className={`fa ${
                                  showPassword ? "fa-eye" : "fa-eye-slash"
                                } password-eye`}
                                onClick={() => setShowPassword(!showPassword)}
                                style={{
                                  position: "absolute",
                                  right: "10px",
                                  top: "50%",
                                  transform: "translateY(-50%)",
                                  cursor: "pointer",
                                }}
                              />
                            </div>
                            <ErrorMessage
                              name="password"
                              component="div"
                              className="error-message"
                            />
                          </div>
                          <button
                            type="submit"
                            className="btn btn-full btn-l font-600 font-13 gradient-highlight mt-4 rounded-s text-white w-100"
                            disabled={isSubmitting}
                          >
                            Sign In as{" "}
                            {activeTab === "user" ? "User" : "Corporate"}
                          </button>

                          <div className="row pt-3 mb-3">
                            <div className="col-5 text-start">
                              <a
                                href="#"
                                onClick={() => setModalType("forgot")}
                                className="color-highlight"
                              >
                                Forgot Password?
                              </a>
                            </div>
                            <div className="col-7 text-end">
                              <a
                                href="#"
                                onClick={() => setModalType("register")}
                                className="color-highlight"
                              >
                                {activeTab === "staff"
                                  ? "Request Corporate Access"
                                  : "Create Account"}
                              </a>
                            </div>
                          </div>
                        </Form>
                      </>
                    )}
                  </Formik>
                </div>
              </div>
            </div>
          </div>

          {/* Dummy Menus */}
          <div
            id="menu-main"
            className="menu menu-box-left rounded-0"
            data-menu-width={280}
          />
          <div
            id="menu-share"
            className="menu menu-box-bottom rounded-m"
            data-menu-height={370}
          />
          <div
            id="menu-colors"
            className="menu menu-box-bottom rounded-m"
            data-menu-height={480}
          />
        </div>
      )}
    </>
  );
};

export default LoginModal;
