import { IEquipmentSet, IItem } from '@rpg-engine/shared';
import React from 'react';
import { RelativeListMenu } from '../../RelativeListMenu';
import { ItemTooltip } from '../Cards/ItemTooltip';
import { MobileItemTooltip } from '../Cards/MobileItemTooltip';
import { useItemSlotDetails } from './context/ItemSlotDetailsContext';
import { useItemSlotDragging } from './context/ItemSlotDraggingContext';

interface IProps {
  dragScale: number | undefined;
  onSelected?: (optionId: string, item: IItem) => void;
  atlasIMG: any;
  atlasJSON: any;
  equipmentSet?: IEquipmentSet | null;
  isContextMenuDisabled?: boolean;
}

export const ItemSlotToolTips = ({
  dragScale,
  onSelected,
  atlasIMG,
  atlasJSON,
  equipmentSet,
  isContextMenuDisabled,
}: IProps): JSX.Element => {
  const { detailsState, updateDetailsState } = useItemSlotDetails();

  const {
    isTooltipVisible,
    isTooltipMobileVisible,
    isContextMenuVisible,
    contextMenuPosition,
    contextActions,
    item,
  } = detailsState;

  const { draggingState } = useItemSlotDragging();

  const { isFocused } = draggingState;

  return (
    <>
      {isTooltipVisible && item && !isFocused && (
        <ItemTooltip
          item={item}
          atlasIMG={atlasIMG}
          atlasJSON={atlasJSON}
          equipmentSet={equipmentSet}
        />
      )}

      {isTooltipMobileVisible && item && (
        <MobileItemTooltip
          item={item}
          atlasIMG={atlasIMG}
          atlasJSON={atlasJSON}
          equipmentSet={equipmentSet}
          closeTooltip={() => {
            updateDetailsState({ isTooltipMobileVisible: false });
          }}
          scale={dragScale}
          options={contextActions}
          onSelected={(optionId: string) => {
            updateDetailsState({
              isContextMenuVisible: false,
            });
            if (item) {
              onSelected?.(optionId, item);
            }
          }}
        />
      )}

      {!isContextMenuDisabled &&
        isContextMenuVisible &&
        contextActions &&
        contextActions.length > 0 && (
          <RelativeListMenu
            options={contextActions}
            onSelected={(optionId: string) => {
              updateDetailsState({ isContextMenuVisible: false });
              if (item) {
                onSelected?.(optionId, item);
              }
            }}
            onOutsideClick={() => {
              updateDetailsState({ isContextMenuVisible: false });
            }}
            pos={contextMenuPosition}
          />
        )}
    </>
  );
};
