import { getItemTextureKeyPath } from '@rpg-engine/shared';
import React from 'react';
import styled from 'styled-components';
import { useCursorPosition } from '../../../hooks/useCursorPosition';
import { SpriteFromAtlas } from '../../shared/SpriteFromAtlas';
import { onRenderStackInfo } from './ItemSlotQty/ItemSlotQty';
import { useItemSlotDragging } from './context/ItemSlotDraggingContext';

const CONTAINER_SIZE = 32;
const OFFSET = CONTAINER_SIZE / 2;

interface IProps {
  atlasJSON: any;
  atlasIMG: any;
  scale?: number;
}

export const DraggedItem = ({
  atlasJSON,
  atlasIMG,
  scale,
}: IProps): JSX.Element | null => {
  const { draggingState } = useItemSlotDragging();

  const { item } = draggingState;

  const { x, y } = useCursorPosition({
    scale,
  });

  if (!item) {
    return null;
  }

  if (x === 0 && y === 0) {
    return null;
  }

  const centeredX = x - OFFSET;
  const centeredY = y - OFFSET;

  const stackInfo = onRenderStackInfo(item?._id ?? '', item?.stackQty ?? 0);

  return (
    <Container>
      <SpriteContainer x={centeredX} y={centeredY}>
        <SpriteFromAtlas
          key={item._id}
          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"
        />
        {stackInfo}
      </SpriteContainer>
    </Container>
  );
};

interface IContainer {
  x: number;
  y: number;
}

const pulse = `
  @keyframes pulse {
    0%, 100% {
      transform: scale(1) rotate(-3deg);
    }
    50% {
      transform: scale(0.95) rotate(-3deg);
    }
  }
`;

const Container = styled.div`
  position: relative;
`;

const SpriteContainer = styled.div.attrs<IContainer>(props => ({
  style: {
    left: `${props.x}px`,
    top: `${props.y}px`,
  },
}))<IContainer>`
  ${pulse}

  position: absolute;
  z-index: 100;
  pointer-events: none;

  width: ${CONTAINER_SIZE}px;
  height: ${CONTAINER_SIZE}px;

  transform: rotate(-3deg);

  filter: grayscale(100%);
  opacity: 0.35;

  animation: pulse 2s infinite;

  .item-slot-qty {
    position: absolute;
    bottom: 0;
    margin-left: 0.8rem;
  }
`;

export default DraggedItem;
