import { FC, useState } from 'react';

import { ThreadItemMenuProps, ThreadItemMenu } from './ThreadItemMenu';

export type ContextMenu = {
  top: number;
  left: number;
};

export type ThreadItemContextMenuProps = Omit<
  ThreadItemMenuProps,
  'onClose' | 'open' | 'anchorReference' | 'anchorPosition'
>;

export const ThreadItemContextMenu: FC<
  React.PropsWithChildren<ThreadItemContextMenuProps>
> = props => {
  const { children, ...menuProps } = props;

  const [contextMenu, setContextMenu] = useState<null | ContextMenu>(null);

  const open = Boolean(contextMenu);

  const openMenu = event => {
    event.preventDefault();

    if (contextMenu === null) {
      setContextMenu({
        top: event.clientY,
        left: event.clientX,
      });
    }
  };

  const closeMenu = () => {
    setContextMenu(null);
  };

  return (
    <div onContextMenu={openMenu}>
      {children}
      <ThreadItemMenu
        {...menuProps}
        open={open}
        onClose={closeMenu}
        anchorReference="anchorPosition"
        anchorPosition={open ? { ...contextMenu } : undefined}
      />
    </div>
  );
};

export default ThreadItemContextMenu;
