import React from 'react';
import { Link } from '@digigov/ui/navigation/Link';
import {
  NavList,
  NavListItemAction,
  NavMenuContentList,
  NavMenuContentListItem,
  NavMenuContent,
  NavMenuContainer,
  NavMenuTitle,
} from '@digigov/ui/navigation/NavList';
import { useNavList } from '@digigov/ui/navigation/NavList/hooks/useNavList';
import { Nav } from '@digigov/ui/navigation/NavList/Nav';
import { NavListAutoProps } from '@digigov/ui/navigation/NavList/types';

export const NavListAuto: React.FC<NavListAutoProps> = ({
  layout,
  links = [],
  ...props
}) => {
  const { registerNavItemMenu, registerNavItem } = useNavList();

  return (
    <Nav {...props}>
      <NavList layout={layout}>
        {links.map((item, key) => (
          <React.Fragment key={key}>
            <NavListItemAction {...registerNavItem(item)}>
              {item.label}
            </NavListItemAction>
            {item.subMenu && (
              <NavMenuContainer
                layout={layout}
                {...registerNavItemMenu(item.name)}
              >
                {(item.subMenuHeading || item.label) && (
                  <NavMenuTitle>
                    {item.subMenuHeading || item.label}
                  </NavMenuTitle>
                )}
                <NavMenuContent>
                  <NavMenuContentList role="menu">
                    {item.subMenu?.map((subMenu, menuIndex) => {
                      return (
                        subMenu?.href && (
                          <NavMenuContentListItem
                            key={menuIndex}
                            role="presentation"
                          >
                            <Link
                              role="menuitem"
                              id={subMenu.name}
                              href={subMenu.href}
                            >
                              {subMenu.label}
                            </Link>
                          </NavMenuContentListItem>
                        )
                      );
                    })}
                  </NavMenuContentList>
                </NavMenuContent>
              </NavMenuContainer>
            )}
          </React.Fragment>
        ))}
      </NavList>
    </Nav>
  );
};

export default NavListAuto;
