import React, { useCallback, forwardRef } from "react";
import { Tooltip } from "../../Tooltip";
import KeyboardArrowRightOutlinedIcon from "@mui/icons-material/KeyboardArrowRightOutlined";
import { NavLink, MemoryRouter } from "react-router-dom";

const ParentItemDiv = forwardRef(({ item, active, showChild, isOpen, onClickRoute, ...rest }, ref) => {
  const hasChildren = Boolean(item.children && item.children.length > 0);
  const isActive = item.value === active;
  const isExpanded = hasChildren && showChild === item.value;

  const handleKeyDown = useCallback(
    (e) => {
      if (e.key === 'Enter' || e.key === ' ') {
        e.preventDefault();
        onClickRoute(item);
      }
    },
    [item, onClickRoute]
  );

  return (
    <div
      ref={ref}
      className={`impact-sidebar-routes-list-item ${isActive ? "route-active" : ""} ${item.isDisabled ? "route-disabled" : ""}`}
      onClick={(e) => onClickRoute(item, e)}
      onKeyDown={handleKeyDown}
      role="menuitem"
      tabIndex={item.isDisabled ? -1 : 0}
      aria-expanded={hasChildren ? isExpanded : undefined}
      aria-current={isActive ? "page" : undefined}
      aria-disabled={item.isDisabled || undefined}
      data-sidebar-item=""
      data-item-type="parent"
      data-item-value={item.value}
      {...(hasChildren ? { 'data-has-children': '' } : {})}
      {...(item.isDisabled ? { 'data-disabled': '' } : {})}
      {...rest}
    >
      <div className="impact-sidebar-routes-list-item-icon">{item.icon}</div>

      {isOpen ? (
        <div className="impact-sidebar-routes-list-item-label">
          <span className="impact-sidebar-routes-list-item-label-text">
            {item.label}
          </span>
          {hasChildren && (
            <div
              className={`impact-sidebar-routes-list-item-children-indicator-horizontal ${isExpanded ? "indicator-turn-up" : ""}`}
              role="presentation"
              aria-hidden="true"
            >
              <KeyboardArrowRightOutlinedIcon />
            </div>
          )}
        </div>
      ) : (
        <>
          {hasChildren && (
            <div
              className="impact-sidebar-routes-list-item-children-indicator-horizontal"
              role="presentation"
              aria-hidden="true"
            >
              <KeyboardArrowRightOutlinedIcon />
            </div>
          )}
          <div className="impact-sidebar-routes-list-item-label" aria-hidden="true">
            {item.label}
          </div>
        </>
      )}
    </div>
  );
});

export const ParentMenu = ({
  isOpen,
  setIsOpen,
  active,
  item,
  showChild,
  setShowChild,
  handleRouteChange,
  isMemoryRouter,
}) => {
  const handleClickOnRoute = (item, event) => {
    if (item.children && item.children.length > 0) {
      if (!isOpen) {
        setIsOpen(true);
      }
      if (item.link) {
        handleRouteChange(item, event);
      }
      if (showChild === item.value) {
        setShowChild(null);
      } else {
        setShowChild(item.value);
      }
    } else {
      handleRouteChange(item, event);
    }
  };

  const itemProps = {
    item,
    active,
    showChild,
    isOpen,
    onClickRoute: handleClickOnRoute,
  };

  if (isOpen) {
    return isMemoryRouter ? (
      <MemoryRouter>
        <NavLink
          to={item?.openInNewPage ? "#" : item.link}
          className="impact-sidebar-routes-list-item-link"
          tabIndex={-1}
        >
          <ParentItemDiv {...itemProps} />
        </NavLink>
      </MemoryRouter>
    ) : (
      <ParentItemDiv {...itemProps} />
    );
  }

  const tooltipTitle =
    item.tooltip && item.tooltip.length > 0 ? item.tooltip : item.label;

  return isMemoryRouter ? (
    <MemoryRouter>
      <Tooltip title={tooltipTitle} orientation="right" variant="tertiary">
        <NavLink
          to={item?.openInNewPage ? "#" : item.link}
          className="impact-sidebar-routes-list-item-link"
          tabIndex={-1}
        >
          <ParentItemDiv {...itemProps} />
        </NavLink>
      </Tooltip>
    </MemoryRouter>
  ) : (
    <Tooltip title={tooltipTitle} orientation="right" variant="tertiary">
      <ParentItemDiv {...itemProps} />
    </Tooltip>
  );
};
