import {
  getItemTextureKeyPath,
  IEquipmentSet,
  ITradeResponseItem,
} from '@rpg-engine/shared';
import capitalize from 'lodash/capitalize';
import React, { useEffect, useState } from 'react';
import styled from 'styled-components';
import { uiColors } from '../../constants/uiColors';
import { uiFonts } from '../../constants/uiFonts';
import SelectArrow from '../Arrow/SelectArrow';
import { ItemInfoWrapper } from '../Item/Cards/ItemInfoWrapper';
import { Ellipsis } from '../shared/Ellipsis';
import { SpriteFromAtlas } from '../shared/SpriteFromAtlas';
import PremiumLabel from './PremiumLabel';

export interface ITradeComponentProps {
  traderItem: ITradeResponseItem;
  onQuantityChange: (
    traderItem: ITradeResponseItem,
    selectedQty: number
  ) => void;
  atlasJSON: any;
  atlasIMG: any;
  selectedQty: number;
  equipmentSet?: IEquipmentSet | null;
  scale?: number;
  isBuy?: boolean;
}

const outerQty = 10;

export const TradingItemRow: React.FC<ITradeComponentProps> = ({
  atlasIMG,
  atlasJSON,
  onQuantityChange,
  traderItem,
  selectedQty,
  equipmentSet,
  scale,
  isBuy,
}) => {
  const [inputQty, setInputQty] = useState(selectedQty.toString());

  useEffect(() => {
    setInputQty(selectedQty.toString());
  }, [selectedQty]);

  const handleQuantityChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const newQty = parseInt(e.target.value, 10);
    if (!isNaN(newQty)) {
      setInputQty(e.target.value);
      onQuantityChange(
        traderItem,
        Math.max(0, Math.min(newQty, traderItem.stackQty ?? 999))
      );
    }
  };

  const handleBlur = () => {
    const newQty = parseInt(inputQty, 10);
    if (isNaN(newQty)) {
      setInputQty(selectedQty.toString());
    }
  };

  const onLeftClick = (qty = 1) => {
    onQuantityChange(traderItem, Math.max(0, selectedQty - qty));
  };

  const onRightClick = (qty = 1) => {
    onQuantityChange(
      traderItem,
      Math.min(traderItem.stackQty ?? 999, selectedQty + qty)
    );
  };

  const renderAccountTypeIndicator = () => {
    if (isBuy && traderItem.canBePurchasedOnlyByPremiumPlans) {
      return traderItem.canBePurchasedOnlyByPremiumPlans.map(accountType => (
        <PremiumLabel key={accountType} accountType={accountType} />
      ));
    }
    return null;
  };

  return (
    <ItemWrapper>
      <ItemIconContainer>
        <SpriteContainer>
          <ItemInfoWrapper
            atlasIMG={atlasIMG}
            atlasJSON={atlasJSON}
            equipmentSet={equipmentSet}
            item={traderItem}
            scale={scale}
          >
            <SpriteFromAtlas
              atlasIMG={atlasIMG}
              atlasJSON={atlasJSON}
              spriteKey={getItemTextureKeyPath(
                {
                  key: traderItem.key,
                  stackQty: traderItem.stackQty || 1,
                  texturePath: traderItem.texturePath,
                  isStackable: traderItem.isStackable,
                },
                atlasJSON
              )}
              imgScale={2}
            />
          </ItemInfoWrapper>
        </SpriteContainer>
      </ItemIconContainer>

      <ItemNameContainer>
        <NameValue>
          <p>
            <Ellipsis maxLines={1} maxWidth="180px">
              {capitalize(traderItem.name)}
            </Ellipsis>
          </p>
          <p>${traderItem.price}</p>
          <p>{renderAccountTypeIndicator()}</p>
        </NameValue>
      </ItemNameContainer>
      <QuantityContainer>
        <SelectArrow
          size={24}
          className="arrow-selector"
          direction="left"
          onPointerDown={() => onLeftClick(outerQty)}
          scale={0.7}
        />
        <StyledArrow
          size={24}
          className="arrow-selector"
          direction="left"
          onPointerDown={() => onLeftClick()}
        />
        <QuantityInput
          type="text"
          value={inputQty}
          onChange={handleQuantityChange}
          onBlur={handleBlur}
        />
        <StyledArrow
          size={24}
          className="arrow-selector"
          direction="right"
          onPointerDown={() => onRightClick()}
        />
        <SelectArrow
          size={24}
          className="arrow-selector"
          direction="right"
          onPointerDown={() => onRightClick(outerQty)}
          scale={0.7}
        />
      </QuantityContainer>
    </ItemWrapper>
  );
};

const StyledArrow = styled(SelectArrow)`
  margin: 0 1.5rem;
`;

const ItemWrapper = styled.div`
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-bottom: 0.5rem;
  padding: 0.25rem;

  &:hover {
    background-color: ${uiColors.darkGray};
  }
`;

const ItemNameContainer = styled.div`
  flex: 60%;
  display: flex;
  align-items: center;
`;

const ItemIconContainer = styled.div`
  display: flex;
  justify-content: flex-start;
  align-items: center;
  flex: 0 0 40px;
`;

const SpriteContainer = styled.div`
  position: relative;
  top: -0.5rem;
  left: 0;
`;

const NameValue = styled.div`
  p {
    font-size: 0.6rem;
    margin: 0;
    line-height: 1.2;
  }
`;

const QuantityContainer = styled.div`
  display: flex;
  min-width: 90px;
  width: 40%;
  justify-content: flex-end;
  align-items: center;
  flex: 30%;
  gap: 2px;
  position: relative;
`;

const QuantityInput = styled.input`
  width: 30px;
  text-align: center;
  background-color: ${uiColors.darkGray};
  color: white;
  border: none;
  padding: 1px;
  font-size: ${uiFonts.size.small};
  position: relative;
  right: 4px;
`;
