// @ts-check
import React from 'react';
import PropTypes from 'prop-types';
import { getProp, getUrl } from '@moonwalker/lifesupport';

import { filterMenuItems } from './menu.utils';

/**
 *
 * Render menu item list
 *
 * @param {import('types').IMenuComponentProps} props
 * @return {React.ReactElement}
 */
export const Menu = (props) => {
  const {
    className,
    as: WrapperComponent,
    authenticated,
    renderItem,
    locale,
    menu,
    isClientRender,
    itemControlMap,

    // properties that we do not pass down
    slug,

    ...restProps
  } = props;

  if (!menu || !menu.items) {
    return null;
  }

  /** @type Array<Lifesupport.MenuListItem> */
  const menuListItems = filterMenuItems(menu.items, {
    authenticated,
    isClientRender,
    itemControlMap
  });

  return (
    <WrapperComponent {...restProps} className={className}>
      {menuListItems.map((menuListItem) => {
        const { label, route, routeSlug } = menuListItem;
        const routePath = getProp(route, 'path') || '';
        const to = getUrl(locale, routePath, routeSlug);

        return renderItem(
          {
            to,
            key: `${to}-${label}`,
            children: label
          },
          menuListItem
        );
      })}
    </WrapperComponent>
  );
};

Menu.propTypes = {
  /** Adopted child class name */
  className: PropTypes.string.isRequired,

  /** Wrapper component */
  as: PropTypes.elementType.isRequired,

  /** Authenticated flag */
  authenticated: PropTypes.bool.isRequired,

  /** Is client rendered flag */
  isClientRender: PropTypes.bool.isRequired,

  /** Item visibility flags from a capsule */
  itemControlMap: PropTypes.objectOf(PropTypes.bool),

  /** Menu data */
  menu: PropTypes.shape({
    items: PropTypes.string
  }),

  /** Locale value */
  locale: PropTypes.string.isRequired,

  /** Render item prop */
  renderItem: PropTypes.func.isRequired,

  /** Menu slug */
  slug: PropTypes.string.isRequired
};

Menu.defaultProps = {
  menu: null,
  itemControlMap: {}
};
