import Decimal from "decimal.js";
import { useMemo } from "react";
import starkString from "starkstring";
import { useMarketTicker } from "../marketTicker";
import { useConvertBaseToQuote } from "../useConvertBaseToQuote";
import { useMarketFilters } from "../useMarketFilters";
import { useStepSize } from "../useStepSize";

export const useStepValues = (
  type: "market" | "limit",
  symbol?: string,
  isTickSize?: boolean,
) => {
  const { toStepSize, toTickSize } = useStepSize(symbol, "limit");
  const { getSymbolMarketTicker } = useMarketTicker();
  const selectedMarket = getSymbolMarketTicker(symbol);
  const convert = useConvertBaseToQuote();

  const { maxQuantity: _maxQuantity } = useMarketFilters({
    selectedMarket,
    type,
  });

  const _maxNotional = useMemo(
    () =>
      selectedMarket
        ? convert(
            _maxQuantity || 0,
            selectedMarket.baseAsset,
            selectedMarket.quoteAsset,
          )
        : 0,
    [convert, _maxQuantity, selectedMarket],
  );

  const maxBase = selectedMarket?.baseCurrency?.availableRemain || 0;
  const maxQuote = selectedMarket?.quoteCurrency?.availableRemain || 0;

  const maxNotional = maxQuote > _maxNotional ? maxQuote : _maxNotional;
  const maxQuantity = maxBase > _maxQuantity ? maxBase : _maxQuantity;

  const expectedValue = (value?: string | null) =>
    starkString(value || "")
      .parseNumber({ decimal: true })
      .toString();

  const onChangeValue = (_value?: string, isBuy?: boolean) => {
    const _numberedValue = starkString(_value || "")
      .parseNumber({ decimal: true })
      .toNumber();

    if (
      isBuy &&
      !isTickSize &&
      new Decimal(_numberedValue || 0).greaterThan(maxNotional || 0)
    ) {
      return maxNotional;
    }
    if (
      !isBuy &&
      !isTickSize &&
      new Decimal(_numberedValue || 0).greaterThan(maxQuantity || 0)
    ) {
      return maxQuantity;
    }

    const _numberedStepValue = isTickSize
      ? Number(
          toTickSize(
            starkString(_value || "")
              .parseNumber({ decimal: true })
              .toNumber(),
            symbol,
          ),
        )
      : Number(
          toStepSize(
            starkString(_value || "")
              .parseNumber({ decimal: true })
              .toNumber(),
          ),
        );

    const _stepValue = isTickSize
      ? toTickSize(
          starkString(_value || "")
            .parseNumber({ decimal: true })
            .toNumber(),
          symbol,
        )
      : toStepSize(
          starkString(_value || "")
            .parseNumber({ decimal: true })
            .toNumber(),
        );

    return _numberedValue > _numberedStepValue ? _stepValue : _value || "";
  };

  return { expectedValue, onChangeValue };
};
