import {
  ITradeRequestItem,
  ITradeResponseItem,
  TradeTransactionType,
} from '@rpg-engine/shared';
import { useState } from 'react';

interface ITradingGoldHook {
  characterAvailableGold: number;
  type: TradeTransactionType;
  traderItems: ITradeResponseItem[];
}

export const useTradingGold = ({
  characterAvailableGold,
  type,
  traderItems,
}: ITradingGoldHook) => {
  const [sum, setSum] = useState(0);
  const [qtyMap, setQtyMap] = useState(new Map<string, number>());

  const isBuy = () => type === 'buy';

  const hasGoldForSale = () =>
    isBuy() ? !(sum > characterAvailableGold) : true;

  const getFinalGold = () =>
    isBuy() ? characterAvailableGold - sum : characterAvailableGold + sum;

  const getTradeItems = (): ITradeRequestItem[] => {
    const items: ITradeRequestItem[] = [];
    traderItems.forEach(item => {
      const qty = qtyMap.get(item.key);
      if (qty) {
        items.push({
          ...item,
          qty,
        });
      }
    });
    return items;
  };

  const updateQuantity = (item: ITradeResponseItem, selectedQty: number) => {
    setQtyMap(new Map(qtyMap.set(item.key, selectedQty)));

    let newSum = 0;
    qtyMap.forEach((qty, key) => {
      const item = traderItems.find(i => i.key === key);
      if (item) newSum += qty * item.price;
    });
    setSum(newSum);
  };

  return {
    sum,
    qtyMap,
    isBuy,
    hasGoldForSale,
    getFinalGold,
    getTradeItems,
    updateQuantity,
  };
};
