import { IEquipmentSet, IItem } from '@rpg-engine/shared';
import { camelCase } from 'lodash';
import React, { useMemo } from 'react';
import styled from 'styled-components';
import { ItemInfo } from './ItemInfo';

export interface IItemInfoDisplayProps {
  item: IItem;
  atlasIMG: any;
  atlasJSON: any;
  equipmentSet?: IEquipmentSet | null;
  isMobile?: boolean;
}

type EquipmentSlotTypes =
  | 'head'
  | 'neck'
  | 'leftHand'
  | 'rightHand'
  | 'ring'
  | 'legs'
  | 'boot'
  | 'accessory'
  | 'armor'
  | 'inventory';

const itemSlotTypes: EquipmentSlotTypes[] = [
  'head',
  'neck',
  'leftHand',
  'rightHand',
  'ring',
  'legs',
  'boot',
  'accessory',
  'armor',
  'inventory',
];

const getSlotType = (
  itemSlotTypes: string[],
  slotType: string,
  subType: string
): keyof IEquipmentSet => {
  if (!itemSlotTypes.includes(slotType)) {
    return subType as keyof IEquipmentSet;
  }
  return slotType as keyof IEquipmentSet;
};

export const ItemInfoDisplay: React.FC<IItemInfoDisplayProps> = ({
  item,
  atlasIMG,
  atlasJSON,
  equipmentSet,
  isMobile,
}) => {
  const itemToCompare = useMemo(() => {
    if (equipmentSet && item.allowedEquipSlotType?.length) {
      const allowedSlotTypeCamelCase = camelCase(item.allowedEquipSlotType[0]);
      const itemSubTypeCamelCase = camelCase(item.subType);

      const slotType = getSlotType(
        itemSlotTypes,
        allowedSlotTypeCamelCase,
        itemSubTypeCamelCase
      );

      const itemSubTypeFromEquipment = Object.values(equipmentSet).find(
        item => camelCase(item?.subType ?? '') === itemSubTypeCamelCase
      );

      const itemFromEquipment = itemSubTypeFromEquipment
        ? itemSubTypeFromEquipment
        : (equipmentSet[slotType] as IItem);

      if (
        itemFromEquipment &&
        (!item._id || itemFromEquipment._id !== item._id)
      ) {
        return itemFromEquipment;
      }
    }

    return undefined;
  }, [equipmentSet, item]);

  return (
    <Flex $isMobile={isMobile}>
      <ItemInfo
        item={item}
        itemToCompare={itemToCompare}
        atlasIMG={atlasIMG}
        atlasJSON={atlasJSON}
      />

      {itemToCompare && (
        <CompareContainer>
          <Equipped>
            <span>Equipped</span>
          </Equipped>
          <ItemInfo
            item={itemToCompare}
            itemToCompare={item}
            atlasIMG={atlasIMG}
            atlasJSON={atlasJSON}
          />
        </CompareContainer>
      )}
    </Flex>
  );
};

const Flex = styled.div<{ $isMobile?: boolean }>`
  display: flex;
  gap: 0.5rem;
  flex-direction: ${({ $isMobile }) => ($isMobile ? 'row-reverse' : 'row')};
  align-items: center;

  @media (max-width: 640px) {
    flex-direction: column-reverse;
    align-items: center;
  }
`;

const Equipped = styled.div`
  position: absolute;
  bottom: 100%;
  left: 50%;
  transform: translateX(-50%);
`;

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