import React from 'react';
import NavMenuContentListBase, {
  NavMenuContentListProps,
} from '@digigov/react-core/NavMenuContentListBase';
export * from '@digigov/react-core/NavMenuContentListBase';

const focusNavListItem = (e, nextItemIndex) => {
  e.preventDefault();
  const id = document.activeElement?.id;
  const menuItems = Array.from(
    e.currentTarget.querySelectorAll(`[role=menuitem]`)
  );
  const currentItem = menuItems.findIndex(
    (x) => (x as HTMLElement).getAttribute('id') === document.activeElement?.id
  );
  if (
    currentItem + nextItemIndex > -1 &&
    currentItem + nextItemIndex < menuItems.length
  ) {
    (menuItems[currentItem + nextItemIndex] as HTMLElement)?.focus();
  } else {
    const menuElement = Array.from(
      document.querySelectorAll(`[aria-controls]`)
    );
    const currentItem = menuElement.findIndex((x) =>
      id?.includes(x.getAttribute('aria-controls') || '')
    );
    if (nextItemIndex > 0) {
      (menuElement[currentItem + nextItemIndex] as HTMLElement)?.focus();
    } else {
      (menuElement[currentItem] as HTMLElement)?.focus();
    }
  }
};

export const NavMenuContentList: React.FC<NavMenuContentListProps> = ({
  children,
  ...props
}) => {
  return (
    <NavMenuContentListBase
      {...props}
      onKeyDown={(event) => {
        switch (event.key) {
          case 'ArrowDown':
          case 'ArrowRight':
            focusNavListItem(event, 1);
            break;
          case 'ArrowUp':
          case 'ArrowLeft':
            focusNavListItem(event, -1);
            break;
          default:
            break;
        }
      }}
    >
      {children}
    </NavMenuContentListBase>
  );
};

export default NavMenuContentList;
