import Decimal from "decimal.js";
import { ControllerRenderProps } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { selectedSymbolStore } from "../../../../store";
import { useMarketTicker } from "../../../marketTicker";
import { useOrderPlacingError } from "../../../useOrderPlacingError";
import { useStepSize } from "../../../useStepSize";
import { useStepValues } from "../../../useStepValues";
import { OcoOrderValues, SellForm } from "../types";

const ControllerPrice = ({
  render,
}: {
  render: (state: {
    field: ControllerRenderProps<OcoOrderValues, "price">;
  }) => any;
}) => {
  const { t } = useTranslation();
  const { setValue, trigger, getValues } = SellForm.useFormContext();
  const { selectedSymbol } = selectedSymbolStore.useState();
  const { toTickSize } = useStepSize(selectedSymbol?.symbol, "limit");

  const { getPriceError } = useOrderPlacingError();

  const { getSymbolMarketTicker } = useMarketTicker();

  const market = getSymbolMarketTicker(selectedSymbol?.symbol);

  const { expectedValue, onChangeValue } = useStepValues(
    "limit",
    selectedSymbol?.symbol,
    true,
  );

  return (
    <SellForm.Controller
      name="price"
      rules={{
        validate: {
          check: (value) => {
            if (
              value &&
              new Decimal(value).lessThanOrEqualTo(market?.lastPrice || 0)
            ) {
              return t("priceShouldBeMoreThanLostPrice");
            }

            return getPriceError({
              symbol: selectedSymbol?.symbol,
              price: Number(value),
            });
          },
        },
      }}
      render={({ field: { onChange, value, ...rest } }) =>
        render({
          field: {
            value: expectedValue(value),
            onChange: (price) => {
              const { amount, limit } = getValues();
              if (price && amount) {
                const stopPriceTotal = toTickSize(
                  new Decimal(amount).mul(Number(price)),
                );
                const limitTotal = toTickSize(
                  new Decimal(amount).mul(Number(limit || 0)),
                );
                if (Number(stopPriceTotal) > Number(limitTotal)) {
                  setValue("total", stopPriceTotal);
                } else {
                  setValue("total", limitTotal);
                }
              } else {
                setValue("total", "");
              }
              onChange(onChangeValue(price) || price);
              trigger(["total"]);
            },
            ...rest,
          },
        })
      }
    />
  );
};

export { ControllerPrice };
