import Decimal from "decimal.js";

import { useTranslation } from "react-i18next";
import starkString from "starkstring";
import { useGetOtcV1PublicOtcMinmaxamount } from "../../services";
import { useDisplayDecimalDigits } from "../useDisplayDecimalDigits";
import { ConvertContext } from "./context";

export const useConvertAmountValidation = () => {
  const { fromAsset, toAsset, lastChangedField } = ConvertContext.useWatch();
  const { truncFix } = useDisplayDecimalDigits();
  const { t } = useTranslation();
  const {
    data: {
      minSourceQuantity,
      minDestinationQuantity,
      maxDestinationQuantity,
      maxSourceQuantity,
    } = {},
  } = useGetOtcV1PublicOtcMinmaxamount(
    {
      sourceCurrencySymbol: fromAsset,
      destinationCurrencySymbol: toAsset,
    },
    { enabled: !!fromAsset && !!toAsset },
  );

  const minimumFrom = truncFix(minSourceQuantity, fromAsset) || 0;
  const maximumFrom = truncFix(maxSourceQuantity, fromAsset) || 0;
  const minimumTo = truncFix(minDestinationQuantity, toAsset) || 0;
  const maximumTo = truncFix(maxDestinationQuantity, toAsset) || 0;

  const checkAmount = (
    value: string | null | undefined,
    mode: "from" | "to",
  ) => {
    if (!value) {
      return undefined;
    }
    const maximum = mode === "from" ? maximumFrom : maximumTo;
    const minimum =
      mode === "from" ? minSourceQuantity : minDestinationQuantity;

    const maximumFormatted = starkString(maximum)
      .scientificNotationToDecimal()
      .toCurrency()
      .toString();
    const minimumFormatted = starkString(minimum || 0)
      .scientificNotationToDecimal()
      .toCurrency()
      .toString();

    if (lastChangedField === mode) {
      if (new Decimal(value).lessThan(minimum || 0)) {
        return t("valueShouldBeMoreThanMinPrice", {
          minPrice: minimumFormatted,
        });
      }
      if (new Decimal(value).greaterThan(maximum || 0)) {
        return t("valueShouldBeLessThanMaxPrice", {
          maxPrice: maximumFormatted,
        });
      }
    }
  };

  return {
    minimumFrom,
    maximumFrom,
    minimumTo,
    maximumTo,
    checkAmount,
  };
};
