import React, { useState, useContext, useRef, useEffect } from "react";
import { UserContext } from "../../../context/user/userContext";
import { getAccessibleEntities, getEntityUrl } from "../../../services/entityService";
import { DialogBox } from "../dialog";
import { hasAccess } from "../../../services/permissionService";
import {
  accessTypes,
  dashboardNames,
} from "../../../constants/enums";
import $ from "jquery";
export const Header = ({
  brandCode,
  selectedModuleName,
  selectedEntityName,
}) => {
  const dialogRef = useRef(null);
  const { state, logout } = useContext(UserContext);
  const [show, SetShow] = useState(false);
  const [showOAMenu, SetShowOAMenu] = useState(false);
  const [showSSRMenu, SetShowSSRMenu] = useState(false);
  const [showRRMenu, SetShowRRMenu] = useState(false);
  const [showRolesUsersMenu, SetShowRolesUsersMenu] = useState(false);
  const [showLocationsMenu, SetShowLocationsMenu] = useState(false);
  const dashboardUrl = getEntityUrl(dashboardNames.DASHBOARD);
  let distinctModules = state.user.distinctModules;
  

  const handleLogout = (e) => {
    logout();
  };

  const handleToggle = () => {
    // SetShow(current => !current);
    SetShow(!show);
    SetShowOAMenu(false);
    SetShowSSRMenu(false);
    SetShowRolesUsersMenu(false);
    SetShowLocationsMenu(false);
  };

  const ref = useRef(null);
  useEffect(() => {
    let handler = (e) => {
      if (!ref.current.contains(e.target)) {
        SetShow(false);
      }
    };
    document.addEventListener("mousedown", handler);
    return () => {
      document.removeEventListener("mousedown", handler);
    };
  }, []);

  const handleOAmenu = () => {
    SetShowOAMenu(!showOAMenu);
  };

  const handleSSRMenu = () => {
    SetShowSSRMenu(!showSSRMenu);
  };
  const handleRRMenu = () => {
    SetShowRRMenu(!showRRMenu);
  };

  const handleRolesUsersMenu = () => {
    SetShowRolesUsersMenu(!showRolesUsersMenu);
  };
  const handleLocationsMenu = () => {
    SetShowLocationsMenu(!showLocationsMenu);
  };

  const canResetPassword = () => {
    const loginUserType =
      state?.user?.userProfile?.loginUserType?.toUpperCase();
    if (loginUserType === "BREAKGLASS" || loginUserType === "FRMUSER") {
      return state?.user?.userProfile?.isPrimaryBrand ?? false;
    }
    return false;
  };
  const canSwitchBrand = () => {
    const hasMultipleBrands = state?.user?.userProfile?.hasMultipleBrands;
    if (hasMultipleBrands !== undefined && hasMultipleBrands === true) {
      return true;
    }
    return false;
  };

  const getDashboard = () => {
    return (
      <React.Fragment>
        <div className="menu-accordian">
          <div className="menu-acc-head">
            <div>
              <a href={dashboardUrl}>Home</a>
            </div>
          </div>
          <div className="menu-any-body"></div>
        </div>
        <div className="dd-link-seperator"></div>
      </React.Fragment>
    );
  };

  
  const getEntityDescription = (eName, eDescription) => {
    return eDescription;
  };

  const getModuleEntity = (entity, i) => {
    const entityName = entity.entityName;
    const displayName = getEntityDescription(
      entity.entityName,
      entity.entityDescription
    );
    const url = getEntityUrl(
      entityName,
      selectedModuleName,
      selectedEntityName
    );
    const showEntity = hasAccess(
      state?.user?.privileges,
      entityName,
      accessTypes.READ
    );
    if (showEntity) {
      return (
        <React.Fragment key={i}>
          <a
            href={url}
            data-value={entityName}
            className="menu-link-block w-inline-block"
            tabIndex="0"
          >
            <div>{displayName}</div>
          </a>
          <div className="dd-link-seperator" />
        </React.Fragment>
      );
    }
    return <React.Fragment></React.Fragment>;
  };

  const getClassHandler = (mName) => {
    if (mName === moduleNames.OrderAheadStatusModule) {
      handleOAmenu();
    }
    if (mName === moduleNames.ManageRolesAndUsersModule) {
      handleRolesUsersMenu();
    }
    if (mName === moduleNames.SmartSellReportingModule) {
      handleSSRMenu();
    }
    if (mName === moduleNames.RevenueManagement) {
      handleRRMenu();
    }
    if (mName === moduleNames.Locations) {
      handleLocationsMenu();
    }
  };

  const getClassVariable = (mName, mainClsName, trueClsName, falseClsName) => {
    let bValue = false;
    switch (mName) {
      case moduleNames.ManageRolesAndUsersModule: {
        bValue = showRolesUsersMenu;
        break;
      }
      case moduleNames.Locations: {
        bValue = showLocationsMenu;
        break;
      }
      case moduleNames.SmartSellReportingModule: {
        bValue = showSSRMenu;
        break;
      }
      case moduleNames.RevenueManagement: {
        bValue = showRRMenu;
        break;
      }
      case moduleNames.OrderAheadStatusModule:
      default: {
        bValue = showOAMenu;
        break;
      }
    }
    return mainClsName + " " + (bValue === true ? trueClsName : falseClsName);
  };

  const hasAtleastTwoModuleAccess = () => {
    const privileges = state.user.privileges;
    let modules = privileges.filter(
      (x) => x.showInMenu === true && x.canRead === true
    );
    let moduleNames = [];
    for (let c = 0; c < modules.length; c++) {
      let m = modules[c];
      if (moduleNames.indexOf(m.moduleName) === -1) {
        moduleNames.push(m.moduleName);
      }
    }
    return moduleNames.length > 1;
  };

  const getModule = (obj, k) => {
    let module = obj;
    let moduleName = obj.moduleName;
    let moduleDisplayName = module.moduleDescription;
    let accessibleEntities = getAccessibleEntities(state.user.privileges, moduleName);
    if (accessibleEntities.length > 0)
      return (
        <React.Fragment key={k}>
          <div className="menu-accordian">
            <div
              className="menu-acc-head"
              onClick={() => {
                getClassHandler(moduleName);
              }}
            >
              <div>{moduleDisplayName}</div>
              <img
                loading="lazy"
                alt=""
                className={getClassVariable(
                  moduleName,
                  "menu-acc-icon",
                  "expand",
                  ""
                )}
              />
            </div>
            <div
              className={getClassVariable(
                moduleName,
                "menu-acc-body",
                "",
                "collapse"
              )}
            >
              {moduleEntities.map((entity, i) => {
                return getModuleEntity(entity, i);
              })}
            </div>
          </div>
        </React.Fragment>
      );
  };

  const getName = () => {
    let userProfile = state?.user?.userProfile;
    let firstName = userProfile?.firstName ?? "";
    let lastName = userProfile?.lastName ?? "";
    let name = firstName + (lastName.length > 0 ? " " + lastName : "");
    return name;
  };

  const getInitials = () => {
    let userProfile = state?.user?.userProfile;
    let firstName = userProfile?.firstName ?? "";
    let lastName = userProfile?.lastName ?? "";
    let initials = firstName?.slice(0, 1) + lastName.slice(0, 1);
    return initials;
  };

  const getDisplayRoleName = () => {
    let userProfile = state?.user?.userProfile;
    return userProfile?.userRoleType;
  };

  const onResetPassword = () => {
    SetShow(false);
    dialogRef.current.handleResetPassword();
  };

  const onSwitchBrand = () => {
    const completeApplicationUrl = `${process.env.REACT_APP_GENERIC_APP_URL}ExternalBrandSelection`;
    const token = state?.token;
    const brandAPIUrl = process.env.REACT_APP_AUTH_API_PRIVATE_URL;
    const isCorporateUser =
      state?.user?.userProfile?.loginUserType?.toUpperCase() ===
      "OKTACORPORATE";
    const corpBrandCode = state?.user?.userProfile?.corpBrandCode;
    const frm = $("form[data-name=form-hidden");

    const getHiddenElement = (name) => {
      return $(frm).find("input[type=hidden][name=" + name + "]");
    };
    const setHiddenElementValue = (name, value) => {
      let hiddenElement = getHiddenElement(name);
      hiddenElement.val(value);
    };
    const fnSubmitToSinglePageApp = () => {
      setHiddenElementValue("hdnToken", token);
      setHiddenElementValue("hdnIsCorporateUser", isCorporateUser);
      setHiddenElementValue("hdnBrandAPIUrl", brandAPIUrl);
      setHiddenElementValue("hdnCorpBrandCode", corpBrandCode);
      frm.attr("action", completeApplicationUrl);
      frm.attr("method", "post");
      frm[0].submit();
    };
    fnSubmitToSinglePageApp();
  };

  const onSendFeedback = () => {
    SetShow(false);
    dialogRef.current.handleSendFeedback();
  };

  return (
    <React.Fragment>
      <DialogBox ref={dialogRef} />
      {canSwitchBrand() ? (
        <div className="blank-container">
          <form data-name="form-hidden">
            <input type="hidden" name="hdnToken" value="" />
            <input type="hidden" name="hdnBrandAPIUrl" value="" />
            <input type="hidden" name="hdnIsCorporateUser" value="" />
            <input type="hidden" name="hdnCorpBrandCode" value="" />
          </form>
        </div>
      ) : (
        <div className="blank-container"></div>
      )}
      <div className="dashboard-header">
        <div className="container menu">
          <div className="dashboard-header">
            <div className="container menu">
              {hasAtleastTwoModuleAccess() && (
                <a
                  href={dashboardUrl}
                  className="main-logo-wrapper w-inline-block"
                >
                  {" "}
                </a>
              )}
              {hasAtleastTwoModuleAccess() === false && (
                <div className="main-logo-wrapper w-inline-block"></div>
              )}

              <div className="menu-link-wrapper">
                <div
                  ref={ref}
                  data-hover="false"
                  data-delay="0"
                  className="menu-dropdown w-dropdown"
                >
                  <div className="menu-dd-toggle w-dropdown-toggle">
                    <div
                      className="hamburger-menu"
                      onClick={(event) => {
                        handleToggle(event);
                      }}
                    >
                      <div className="ham-line" />
                      <div className="ham-line" />
                      <div className="ham-line" />
                    </div>
                  </div>
                  <nav
                    className={`menu-dd-list w-dropdown-list ${
                      show ? "w--open" : "w-close"
                    }`}
                  >
                    <div className="dd-triangle" />
                    <div className="dd-link-wrapper">
                      <div className="menu-profile-header">
                        <div className="user-profile-icon">{getInitials()}</div>
                        <div className="user-profile-title">
                          <div className="user-title">{getName()}</div>
                          <div className="user-role">
                            {getDisplayRoleName()}
                          </div>
                        </div>
                      </div>
                      {hasAtleastTwoModuleAccess() && getDashboard()}
                      {distinctModules.length > 0 &&
                        distinctModules.map((obj, k) => {
                          return getModule(obj, k);
                        })}
                      <div className="dd-link-seperator" />
                      <div
                        onClick={onSendFeedback}
                        className="menu-link-block w-inline-block"
                      >
                        <div className="dd-link-icon feedback" />
                        <div>Feedback/Support</div>
                      </div>
                      <div className="dd-link-seperator" />
                      {canResetPassword() && (
                        <React.Fragment>
                          <div
                            onClick={onResetPassword}
                            className="menu-link-block w-inline-block"
                          >
                            <div className="dd-link-icon" />
                            <div>Reset Password</div>
                          </div>
                          <div className="dd-link-seperator" />
                        </React.Fragment>
                      )}
                      {canSwitchBrand() && (
                        <React.Fragment>
                          <div
                            onClick={onSwitchBrand}
                            className="menu-link-block w-inline-block"
                          >
                            <div className="dd-link-icon dd-link-switchbrand" />
                            <div>Switch Brand</div>
                          </div>
                          <div className="dd-link-seperator" />
                        </React.Fragment>
                      )}

                      <div
                        onClick={handleLogout}
                        className="menu-link-block w-inline-block"
                      >
                        <div className="dd-link-icon logout" />
                        <div>Logout</div>
                      </div>
                    </div>
                  </nav>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </React.Fragment>
  );
};


