import { IItem, ItemContainerType } from '@rpg-engine/shared';
import { Meta, Story } from '@storybook/react';
import React, { useState } from 'react';
import {
  IItemContainerProps,
  ItemContainer,
} from '../../../components/Item/Inventory/ItemContainer';
import { RPGUIRoot } from '../../../components/RPGUI/RPGUIRoot';
import { ScalableContainer } from '../../../components/shared/ScalableContainer';
import { UI_BREAKPOINT_SMALL_LAPTOP } from '../../../constants/uiBreakpoints';
import { useShortcuts } from '../../../hooks/useShortcuts';
import atlasJSON from '../../../mocks/atlas/items/items.json';
import atlasIMG from '../../../mocks/atlas/items/items.png';
import { equipmentSetMock } from '../../../mocks/equipmentSet.mocks';
import { itemContainerMock } from '../../../mocks/itemContainer.mocks';

const meta: Meta = {
  title: 'UI/Containers/Item Container',
  component: ItemContainer,
};

export default meta;

const onSelected = (payload: string, item: IItem) => {
  console.log('onSelected', payload, item);
};

// THIS IS ONLY LONG-BOW EXAMPLE FOR DRAG AND DROP
let dragItem: IItem | null = null;
let dropItem: IItem | null = null;
let allowedToDrop = false;
let dragSlot = -1;
let dropSlot = -1;

interface ITemplateProps {
  type: ItemContainerType;
  scale?: number;
}

const Template: Story<IItemContainerProps & ITemplateProps> = ({
  type,
  scale,
}) => {
  const mock = itemContainerMock({ name: type });

  const [itemContainer, setItemContainer] = useState(mock);

  const { shortcuts, setItemShortcut, removeShortcut } = useShortcuts({
    itemContainer: mock,
  });

  const CoreItemContainer = () => (
    <ItemContainer
      itemContainer={itemContainer}
      onClose={() => console.log('closing item container')}
      onMouseOver={() => {}}
      onSelected={onSelected}
      onItemClick={() => {}}
      checkIfItemCanBeMoved={() => allowedToDrop}
      onItemDragEnd={quantity => {
        // THIS IS ONLY LONG-BOW EXAMPLE FOR DRAG AND DROP

        if (quantity === 0) {
          setItemContainer({ ...itemContainer });
        } else if (allowedToDrop && dropSlot !== -1) {
          const newContainer = { ...itemContainer };

          if (quantity && dragItem && dragItem.stackQty) {
            newContainer.slots[dropSlot] = {
              ...dragItem,
              stackQty: quantity + (dropItem?.stackQty || 0),
            };

            if (dragItem.stackQty - quantity === 0)
              newContainer.slots[dragSlot] = null;
            else
              newContainer.slots[dragSlot] = {
                ...dragItem,
                stackQty: dragItem.stackQty - quantity,
              };
          } else {
            newContainer.slots[dropSlot] = dragItem;
            newContainer.slots[dragSlot] = null;
          }
          setTimeout(() => {
            setItemContainer(newContainer);
          }, 100);
        }

        allowedToDrop = false;
        dropSlot = -1;
        dropItem = null;
        dragItem = null;
      }}
      onItemDragStart={(item, slotIndex) => {
        dragItem = item;
        dragSlot = slotIndex;
      }}
      onItemPlaceDrop={(item, slotIndex) => {
        // THIS IS ONLY LONG-BOW EXAMPLE FOR DRAG AND DROP

        if (!item || (dragItem?.key === item?.key && dragSlot !== slotIndex)) {
          allowedToDrop = true;
          dropSlot = slotIndex;
          dropItem = item ? item : null;
        } else {
          allowedToDrop = false;
          dropSlot = -1;
          dropItem = null;
        }
      }}
      onOutsideDrop={(item, pos) => console.log('drop', item, pos)}
      type={type}
      atlasIMG={atlasIMG}
      atlasJSON={atlasJSON}
      shortcuts={shortcuts}
      setItemShortcut={setItemShortcut}
      removeShortcut={removeShortcut}
      equipmentSet={equipmentSetMock}
      isDepotSystem
      scale={scale}
    />
  );

  return (
    <RPGUIRoot>
      {scale ? (
        <ScalableContainer
          scale={scale}
          centralize={false}
          breakPoint={UI_BREAKPOINT_SMALL_LAPTOP}
        >
          <CoreItemContainer />
        </ScalableContainer>
      ) : (
        <CoreItemContainer />
      )}
    </RPGUIRoot>
  );
};

export const Inventory = Template.bind({});
Inventory.args = {
  type: ItemContainerType.Inventory,
};

export const Depot = Template.bind({});
Depot.args = {
  type: ItemContainerType.Depot,
};
