import React, { useRef, useEffect, useLayoutEffect, useCallback } from "react";
import { NavLink, MemoryRouter } from "react-router-dom";

export const ChildMenu = ({
  parent,
  active,
  menu,
  showChild,
  handleRouteChange,
  isMemoryRouter,
}) => {
  const containerRef = useRef(null);

  const updateBeforeHeight = () => {
    const container = containerRef.current;
    if (container) {
      const contentHeight = container.scrollHeight;
      container.style.setProperty("--before-height", `${contentHeight}px`);
    }
  };

  useLayoutEffect(() => {
    updateBeforeHeight();
    window.addEventListener("resize", updateBeforeHeight);
    return () => {
      window.removeEventListener("resize", updateBeforeHeight);
    };
  }, []);

  useEffect(() => {
    updateBeforeHeight();
  }, [menu]);

  const makeKeyDownHandler = useCallback(
    (child) => (e) => {
      if (e.key === 'Enter' || e.key === ' ') {
        e.preventDefault();
        handleRouteChange(parent, child);
      }
    },
    [parent, handleRouteChange]
  );

  const childItemProps = (child) => ({
    role: 'menuitem',
    tabIndex: child.isDisabled ? -1 : 0,
    'aria-current': child.value === active ? 'page' : undefined,
    'aria-disabled': child.isDisabled || undefined,
    'data-sidebar-item': '',
    'data-item-type': 'child',
    'data-item-value': child.value,
    'data-parent-value': parent.value,
    ...(child.isDisabled ? { 'data-disabled': '' } : {}),
    onKeyDown: makeKeyDownHandler(child),
  });

  return (
    <div
      className={`impact-sidebar-routes-list-children ${
        showChild === parent.value ? "child-route-visible" : ""
      }`}
      ref={containerRef}
      role="group"
      aria-hidden={showChild !== parent.value ? true : undefined}
      data-nav-collapsed={showChild !== parent.value ? "true" : undefined}
    >
      {menu.map((child) => {
        return isMemoryRouter ? (
          <MemoryRouter key={child.value}>
            <NavLink
              to={child?.openInNewPage ? "#" : child.link}
              className="impact-sidebar-routes-list-item-link"
              tabIndex={-1}
              aria-hidden="true"
            >
              <div
                className={`impact-sidebar-routes-list-item-children ${
                  child.value === active ? "child-route-active" : ""
                } ${child.isDisabled ? "child-route-disabled" : ""}`}
                onClick={(event) => handleRouteChange(parent, child, event)}
                {...childItemProps(child)}
              >
                <div className="impact-sidebar-routes-list-item-child-icon">
                  {child.icon}
                </div>
                <div className="impact-sidebar-routes-list-item-child-label">
                  {child.label}
                </div>
              </div>
            </NavLink>
          </MemoryRouter>
        ) : (
          <div
            key={child.value}
            className={`impact-sidebar-routes-list-item-children ${
              child.value === active ? "child-route-active" : ""
            } ${child.isDisabled ? "child-route-disabled" : ""}`}
            onClick={(event) => handleRouteChange(parent, child, event)}
            {...childItemProps(child)}
          >
            <div className="impact-sidebar-routes-list-item-child-icon">
              {child.icon}
            </div>
            <div className="impact-sidebar-routes-list-item-child-label">
              {child.label}
            </div>
          </div>
        );
      })}
    </div>
  );
};
