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 { BuyForm, OcoOrderValues } from "../types";

const ControllerPrice = ({
  render,
}: {
  render: (state: {
    field: ControllerRenderProps<OcoOrderValues, "price">;
  }) => any;
}) => {
  const { t } = useTranslation();
  const { selectedSymbol } = selectedSymbolStore.useState();

  const { getPriceError } = useOrderPlacingError();
  const { setValue, getValues, trigger } = BuyForm.useFormContext();

  const { toTickSize } = useStepSize(selectedSymbol?.symbol, "limit");

  const { getSymbolMarketTicker } = useMarketTicker();

  const market = getSymbolMarketTicker(selectedSymbol?.symbol);

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

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

            return getPriceError({
              symbol: selectedSymbol?.symbol,
              price: Number(value),
            });
          },
        },
      }}
      render={({ field: { onChange, value, ...rest } }) =>
        render({
          field: {
            value: expectedValue(value),
            onChange: (_value) => {
              const { amount, limit } = getValues();
              if (_value && amount) {
                const stopPriceTotal = toTickSize(
                  new Decimal(amount).mul(Number(_value)),
                );
                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(_value) || _value);
              trigger(["total"]);
            },
            ...rest,
          },
        })
      }
    />
  );
};

export { ControllerPrice };
