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 cssVariables = {
    ...(linkColor && { '--hscl-navigationMenu-color': linkColor }),
    ...(linkColorHover && {
      '--hscl-navigationMenu-color-hover': linkColorHover,
    }),
    ...(backgroundColor && {
      '--hscl-navigationMenu-backgroundColor': backgroundColor,
    }),
    ...(backgroundColorHover && {
      '--hscl-navigationMenu-backgroundColor-hover': backgroundColorHover,
    }),
    ...(submenuLinkColor && {
      '--hscl-navigationMenu-submenu-color': submenuLinkColor,
    }),
    ...(submenuLinkColorHover && {
      '--hscl-navigationMenu-submenu-color-hover': submenuLinkColorHover,
    }),
    ...(submenuBackgroundColor && {
      '--hscl-navigationMenu-submenu-backgroundColor': submenuBackgroundColor,
    }),
    ...(submenuBackgroundColorHover && {
      '--hscl-navigationMenu-submenu-backgroundColor-hover':
        submenuBackgroundColorHover,
    }),
  };

  return (
    <nav
      ref={navRef}
      className={cx(styles.navigationMenu, className)}
      style={{ ...cssVariables, ...style }}
      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;
