import {
  getItemTextureKeyPath,
  IItem,
  ItemContainerType,
  ItemQualityLevel,
  ItemSlotType,
} from '@rpg-engine/shared';
import React from 'react';
import { v4 as uuidv4 } from 'uuid';
import { SpriteFromAtlas } from '../../shared/SpriteFromAtlas';
import { ErrorBoundary } from './ErrorBoundary';
import { onRenderGems } from './ItemGem';
import { EquipmentSlotSpriteByType } from './ItemSlot';
import { onRenderStackInfo } from './ItemSlotQty/ItemSlotQty';

interface IProps {
  containerType: ItemContainerType | null | undefined;
  atlasJSON: any;
  atlasIMG: any;
  slotSpriteMask: ItemSlotType | null | undefined;
  item: IItem | null;
}

export const ItemSlotRenderer: React.FC<IProps> = ({
  containerType,
  atlasJSON,
  atlasIMG,
  slotSpriteMask,
  item,
}) => {
  const renderStackInfo = (item: IItem) => {
    return (
      item.stackQty &&
      item.stackQty > 1 &&
      onRenderStackInfo(item._id, item.stackQty)
    );
  };

  const renderGems = (item: IItem) => {
    return item.attachedGems && onRenderGems(item);
  };

  const renderItem = (item: IItem | null) => {
    if (!item?.texturePath) {
      return null;
    }

    return (
      <ErrorBoundary key={item._id}>
        {item.quality && item.quality !== ItemQualityLevel.Normal && (
          <div className="quality-star">★</div>
        )}
        <SpriteFromAtlas
          atlasIMG={atlasIMG}
          atlasJSON={atlasJSON}
          spriteKey={getItemTextureKeyPath(
            {
              key: item.texturePath,
              texturePath: item.texturePath,
              stackQty: item.stackQty || 1,
              isStackable: item.isStackable,
            },
            atlasJSON
          )}
          imgScale={3}
          imgClassname="sprite-from-atlas-img--item"
          tintColor={item.tintColor}
        />
        {renderStackInfo(item)}
        {renderGems(item)}
      </ErrorBoundary>
    );
  };

  const renderEquipment = (itemToRender: IItem | null) => {
    if (
      !itemToRender?.texturePath ||
      !itemToRender.allowedEquipSlotType?.includes(slotSpriteMask!)
    ) {
      return (
        <ErrorBoundary key={uuidv4()}>
          <SpriteFromAtlas
            key={uuidv4()}
            atlasIMG={atlasIMG}
            atlasJSON={atlasJSON}
            spriteKey={EquipmentSlotSpriteByType[slotSpriteMask!]}
            imgScale={3}
            grayScale={true}
            opacity={0.4}
            imgClassname="sprite-from-atlas-img--item"
          />
        </ErrorBoundary>
      );
    }

    return renderItem(itemToRender);
  };

  const onRenderSlot = (itemToRender: IItem | null) => {
    switch (containerType) {
      case ItemContainerType.Equipment:
        return renderEquipment(itemToRender);
      default:
        return renderItem(itemToRender);
    }
  };

  return onRenderSlot(item);
};
