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

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

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

  return (
    <SellForm.Controller
      name="price"
      rules={{
        validate: {
          check: (value) => {
            return getPriceError({
              symbol: selectedSymbol?.symbol,
              price: Number(value),
            });
          },
        },
      }}
      render={({ field: { onChange, value, ...rest } }) =>
        render({
          field: {
            value: expectedValue(value),
            onChange: (_value) => {
              onChange(onChangeValue(_value) || _value);
              const { amount } = getValues();
              setValue(
                "total",
                amount && _value
                  ? toTickSize(new Decimal(amount).mul(Number(_value)))
                  : "",
              );
              trigger(["total"]);
            },
            ...rest,
          },
        })
      }
    />
  );
};

export { ControllerPrice };
