import React, { useRef, useState } from 'react';
import { SilkeButton, SilkeButtonProps } from '../silke-button';
import { usePopoverRequestClose } from '../silke-popover/popover-context';
import { SilkeContextMenu, SilkeContextMenuItems } from './silke-context-menu';
import { SilkeBox } from '../silke-box';
import styles from './silke-context-menu.scss';

export type SilkeContextMenuItemProps = {
  label: React.ReactNode;
  kind?: 'default' | 'danger' | 'selected';
  width?: number;
  items?: SilkeContextMenuItems;
  /** Used internally to keep track of menu and closing */
  subItem?: boolean;
} & Omit<
  SilkeButtonProps,
  'height' | 'width' | 'align' | 'vAlign' | 'hAlign' | 'kind' | 'onMouseEnter' | 'onMouseLeave'
>;

export const SilkeContextMenuItem = ({
  label,
  kind,
  items,
  width,
  icon,
  subItem,
  onClick,
  selected,
  leftIcon,
  ...rest
}: SilkeContextMenuItemProps) => {
  const cl = [styles.item];
  const ref = useRef<HTMLButtonElement>(null);
  const requestCloseMenu = usePopoverRequestClose('contextmenu');
  const requestCloseSub = usePopoverRequestClose('contextmenu.sub');

  if (selected) cl.push(styles.selected);
  if (leftIcon) cl.push(styles.leftIcon);

  const [showSub, setShowSub] = useState(false);
  return (
    <SilkeBox column hPad="xs">
      <SilkeButton
        ref={ref}
        label={label}
        kind={kind === 'danger' ? 'danger' : 'ghost'}
        size="base"
        hAlign="start"
        icon={items ? 'right' : icon}
        style={{ padding: 'var(--space-s)' }}
        onClick={(e) => {
          if (!items) requestCloseMenu();
          if (onClick) onClick(e);
        }}
        onMouseEnter={(e) => {
          // If items then open this sub menu
          // else request to close all other sub menus (if not a sub itself)
          if (items) setShowSub(true);
          else if (!subItem) requestCloseSub();
        }}
        onKeyUp={(e) => {
          if ((e.key === 'ArrowRight' || e.key === 'Enter') && items) {
            e.stopPropagation();
            e.preventDefault();
            setShowSub(true);
          }
        }}
        className={cl.join(' ')}
        leftIcon={leftIcon}
        {...rest}
      />
      {showSub && items && (
        <SilkeContextMenu
          contextId="contextmenu.sub"
          onRequestClose={() => setShowSub(false)}
          anchor={ref}
          items={items}
          width={width}
          offsetX={3}
          subMenu={true}
          targetOrigin="top-left"
          anchorOrigin="top-right"
        />
      )}
    </SilkeBox>
  );
};
