import React, { forwardRef } from "react";
import classNames from "classnames";
import { bem } from "../../utilities/bem";
import { useMenuContext } from "../MenuRenderer";

const cn = "Menu";

export interface MenuItemProps {
  as?: any;
  onClick?: () => void;
  isSelected?: boolean;
  isHighlighted?: boolean;
  [key: string]: any;
}

export const MenuItem = forwardRef<MenuItemProps, any>(
  (
    {
      children,
      className,
      isSelected = false,
      isHighlighted = false,
      as: Component = "button",
      onClick,
      ...rest
    },
    ref,
  ) => {
    const { onClose, itemProps } = useMenuContext();
    const clickHandler = () => {
      if (typeof onClick === "function") {
        onClick();
      }
      if (typeof onClose === "function") {
        onClose();
      }
    };

    return (
      <Component
        ref={ref}
        className={classNames([
          bem(cn, { e: "item" }),
          isSelected && bem(cn, { e: "item", m: "isSelected" }),
          isHighlighted && bem(cn, { e: "item", m: "isHighlighted" }),
          className,
        ])}
        onClick={clickHandler}
        {...itemProps}
        {...rest}
      >
        {children}
      </Component>
    );
  },
);
