import React, { useContext } from 'react';
import PropTypes from 'prop-types';
import { compose, branch } from 'recompose';
import {
  Link,
  Localization,
  User,
  withData,
  withClientRender,
  withCapsule
} from '@moonwalker/lifesupport';
import { MenuQuery } from '@moonwalker/lifesupport/lib/queries/menu';

import { Menu as MenuComponent } from './menu.component';

/**
 * Default menu list item
 *
 * @param {import('types').IRenderItemProps} menuListItemProps
 * @returns {React.ReactElement}
 */
const defaultRenderItem = (menuListItemProps) => <Link {...menuListItemProps} />;

/**
 *
 * Menu component - list of menu-list-item
 *
 * @param {import('types').IMenuProps} props;
 * @return {React.ReactElement}
 */
export const Menu = (props) => {
  const { itemControlCapsule } = props;
  const { locale } = useContext(Localization);
  const user = useContext(User);

  // @TODO use hooks
  const BaseComponent = compose(
    withData(MenuQuery),
    withClientRender,
    branch(
      () => itemControlCapsule?.length > 0,
      withCapsule({ componentType: itemControlCapsule, nameSpace: 'itemControlMap' })
    )
  )(MenuComponent);

  return <BaseComponent {...props} locale={locale} authenticated={Boolean(user)} />;
};

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

  /** Menu slug */
  slug: PropTypes.string.isRequired,

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

  /** Render MenuListItem render prop */
  renderItem: PropTypes.func,

  /** Menu related capsule to control which items will be rendered */
  itemControlCapsule: PropTypes.string
};

Menu.defaultProps = {
  className: '',
  as: 'nav',
  renderItem: defaultRenderItem,
  itemControlCapsule: null
};

export * from './menu.utils';
