import MenuItem from '../../MenuItem/index.js';
import Flex from '../../../Flex/index.js';
import styles from './index.module.scss';
import { NavigationMenuProps } from './types.js';
import cx from '../../../utils/classname.js';
import { addIdsToMenuItems } from '../../utils/transformMenuData.js';
import { useMemo, useRef } from 'react';

const NavigationMenuIsland = ({
  justifyMenu = 'flex-start',
  className = '',
  navAriaLabel = 'Navigation',
  style = {},
  linkColor,
  linkColorHover,
  backgroundColor,
  backgroundColorHover,
  submenuLinkColor,
  submenuLinkColorHover,
  submenuBackgroundColor,
  submenuBackgroundColorHover,
  menuData,
}: NavigationMenuProps) => {
  if (!menuData?.pagesTree?.children) return null;

  const menuItems = useMemo(
    () => addIdsToMenuItems(menuData.pagesTree.children),
    [menuData]
  );
  const level = 1;
  const navRef = useRef<HTMLElement>(null);

  const handleKeyDown = (event: React.KeyboardEvent) => {
    if (event.key === 'ArrowDown') {
      event.preventDefault();
      navRef.current?.querySelector('li')?.focus();
    }
  };

  const inlineStyles: React.CSSProperties &
    Record<`--hs-${string}`, string> = {
    ...(linkColor && { '--hs-navigationMenu-color': linkColor }),
    ...(linkColorHover && {
      '--hs-navigationMenu-color-hover': linkColorHover,
    }),
    ...(backgroundColor && {
      '--hs-navigationMenu-backgroundColor': backgroundColor,
    }),
    ...(backgroundColorHover && {
      '--hs-navigationMenu-backgroundColor-hover': backgroundColorHover,
    }),
    ...(submenuLinkColor && {
      '--hs-navigationMenu-submenu-color': submenuLinkColor,
    }),
    ...(submenuLinkColorHover && {
      '--hs-navigationMenu-submenu-color-hover': submenuLinkColorHover,
    }),
    ...(submenuBackgroundColor && {
      '--hs-navigationMenu-submenu-backgroundColor': submenuBackgroundColor,
    }),
    ...(submenuBackgroundColorHover && {
      '--hs-navigationMenu-submenu-backgroundColor-hover':
        submenuBackgroundColorHover,
    }),
    ...style,
  };

  return (
    <nav
      ref={navRef}
      className={cx(styles.navigationMenu, className)}
      style={inlineStyles}
      tabIndex={0}
      onKeyDown={handleKeyDown}
      aria-label={navAriaLabel}
    >
      <Flex
        as="ul"
        direction="row"
        className={styles.navList}
        justifyContent={justifyMenu}
      >
        {menuItems.map(item => (
          <MenuItem
            key={item._id}
            item={item}
            level={level}
            addArrows
            useNavigationControls
          />
        ))}
      </Flex>
    </nav>
  );
};

export default NavigationMenuIsland;
