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

const ControllerTotal = ({
  render,
}: {
  render: (state: {
    field: ControllerRenderProps<MarketOrderValues, "total">;
  }) => any;
}) => {
  const { selectedSymbol } = selectedSymbolStore.useState();
  const { selectedOption } = SellForm.useWatch();
  const { setValue, trigger, reset } = SellForm.useFormContext();

  const { getSymbolMarketTicker } = useMarketTicker();
  const currentTicker = getSymbolMarketTicker(selectedSymbol?.symbol);
  const { toStepSize } = useStepSize(selectedSymbol?.symbol, "market");
  const { getTotalError } = useOrderPlacingError();

  return (
    <SellForm.Controller
      name="total"
      rules={{
        validate: {
          check: (value) => {
            if (selectedOption.value !== "total") {
              return;
            }

            if (!Number(value)) {
              setValue("slider", 0);
              return;
            }

            return getTotalError({
              symbol: selectedSymbol?.symbol,
              side: "Sell",
              total: Number(value),
            });
          },
        },
      }}
      render={({ field: { onChange, ...rest } }) =>
        render({
          field: {
            onChange: (_value) => {
              if (selectedOption.value !== "total") {
                return;
              }

              setValue(
                "amount",
                _value && currentTicker?.lastPrice
                  ? toStepSize(new Decimal(_value).div(currentTicker.lastPrice))
                  : "",
              );

              onChange(_value);
              trigger(["amount", "total"]);
            },
            ...rest,
          },
        })
      }
    />
  );
};

export { ControllerTotal };
