import React from 'react';

import { FC } from 'react';

import { onKeyDown } from '../../../../utils/onKeyDown';

import { DesktopMenuItem } from '../Desktop/DesktopMenuItem';

import { navIconStyling, desktopNavListItemStyling, topLevelMenuItem } from '../header.styles';

import { NavProps } from '../../header.types';
import { Icon } from '../../../../molecules/Icon';
import { cssMerge } from '../../../../utils/cssMerge';
import { desktopNavStyling } from '../header.styles';
import { isActiveParent } from '../../utils/functions';

export const DesktopNav: FC<NavProps> = ({ menus, openMenu, setOpenMenu, className }) => {
  return (
    <ul className={cssMerge('!tw-pl-0 !tw-list-none tw-flex tw-gap-8', className)}>
      {menus &&
        menus.map((menu, index: number) => {
          if (!menu) {
            return null;
          }
          const isOpen = index === openMenu;
          const menuItems = menu && menu.menuItems;

          return (
            <li
              key={index}
              onMouseEnter={() => setOpenMenu(index)}
              onKeyDown={e => onKeyDown(e, () => setOpenMenu(index))}
              tabIndex={0}
              className={cssMerge(desktopNavListItemStyling({ color: menu.colorScheme }))}
            >
              {menu.heading && (
                <>
                  <span className={topLevelMenuItem({ active: isActiveParent(menu) })}>{menu.heading}</span>
                  <Icon id="chevron" className={cssMerge(navIconStyling({ isOpen }))} stroke="currentColor" size={12} />
                  {menuItems && isOpen && (
                    <ul className={cssMerge(desktopNavStyling())}>
                      {menuItems.map((menuItem, index) => (
                        <DesktopMenuItem
                          key={menuItem.heading}
                          iconColor={menu.colorScheme}
                          isSibling={index !== 0}
                          {...menuItem}
                        />
                      ))}
                    </ul>
                  )}
                </>
              )}
            </li>
          );
        })}
    </ul>
  );
};
