"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "OrderEntry", {
    enumerable: true,
    get: function() {
        return OrderEntry;
    }
});
const _jsxruntime = require("react/jsx-runtime");
const _react = /*#__PURE__*/ _interop_require_wildcard(require("react"));
const _button = /*#__PURE__*/ _interop_require_default(require("../../button"));
const _text = require("../../text");
const _input = require("../../input");
const _slider = require("../../slider");
const _divider = require("../../divider");
const _orderOptions = require("./sections/orderOptions");
const _hooks = require("@orderly.network/hooks");
const _types = require("@orderly.network/types");
const _modal = require("../../modal");
const _orderConfirmViewnew = require("./sections/orderConfirmView.new");
const _toast = require("../../toast");
const _utils = require("@orderly.network/utils");
const _mSelect = require("../../select/mSelect");
const _css = require("../../utils/css");
const _utils1 = require("../../slider/utils");
const _freeCollat = require("./sections/freeCollat");
const _setInfo = require("./sections/setInfo");
const _accountStatus = require("../accountStatus");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
function _getRequireWildcardCache(nodeInterop) {
    if (typeof WeakMap !== "function") return null;
    var cacheBabelInterop = new WeakMap();
    var cacheNodeInterop = new WeakMap();
    return (_getRequireWildcardCache = function(nodeInterop) {
        return nodeInterop ? cacheNodeInterop : cacheBabelInterop;
    })(nodeInterop);
}
function _interop_require_wildcard(obj, nodeInterop) {
    if (!nodeInterop && obj && obj.__esModule) {
        return obj;
    }
    if (obj === null || typeof obj !== "object" && typeof obj !== "function") {
        return {
            default: obj
        };
    }
    var cache = _getRequireWildcardCache(nodeInterop);
    if (cache && cache.has(obj)) {
        return cache.get(obj);
    }
    var newObj = {
        __proto__: null
    };
    var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;
    for(var key in obj){
        if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) {
            var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;
            if (desc && (desc.get || desc.set)) {
                Object.defineProperty(newObj, key, desc);
            } else {
                newObj[key] = obj[key];
            }
        }
    }
    newObj.default = obj;
    if (cache) {
        cache.set(obj, newObj);
    }
    return newObj;
}
const { Segmented: SegmentedButton } = _button.default;
var InputType;
(function(InputType) {
    InputType[InputType["PRICE"] = 0] = "PRICE";
    InputType[InputType["TRIGGER_PRICE"] = 1] = "TRIGGER_PRICE";
    InputType[InputType["QUANTITY"] = 2] = "QUANTITY";
    InputType[InputType["TOTAL"] = 3] = "TOTAL";
    InputType[InputType["NONE"] = 4] = "NONE";
})(InputType || (InputType = {}));
const OrderEntry = /*#__PURE__*/ (0, _react.forwardRef)((props, ref)=>{
    const { freeCollateral, symbolConfig, maxQty, symbol, // side,
    // onSideChange,
    // onReduceOnlyChange,
    metaState, formattedOrder, helper, disabled, markPrice } = props;
    const { side, isStopOrder } = formattedOrder;
    // const totalInputFocused = useRef<boolean>(false);
    // const priceInputFocused = useRef<boolean>(false);
    const quantityInputFocused = (0, _react.useRef)(false);
    const [errorsVisible, setErrorsVisible] = (0, _react.useState)(false);
    const isClickForm = (0, _react.useRef)(false);
    const currentFocusInput = (0, _react.useRef)(4);
    const priceInputRef = (0, _react.useRef)(null);
    const triggerPriceInputRef = (0, _react.useRef)(null);
    const isTablet = (0, _hooks.useMediaQuery)(_types.MEDIA_TABLET);
    const [needConfirm, setNeedConfirm] = (0, _hooks.useLocalStorage)("orderly_order_confirm", true);
    const baseDP = symbolConfig?.base_dp;
    const ee = (0, _hooks.useEventEmitter)();
    const isMarketOrder = [
        _types.OrderType.MARKET,
        _types.OrderType.STOP_MARKET
    ].includes(formattedOrder.order_type || _types.OrderType.LIMIT);
    (0, _react.useEffect)(()=>{
        // handle orderbook item click event
        const orderbookItemClickHandler = (item)=>{
            if (currentFocusInput.current === 1) {
                if (formattedOrder.order_type === _types.OrderType.STOP_LIMIT || formattedOrder.order_type === _types.OrderType.STOP_MARKET) {
                    props.onFieldChange("trigger_price", (0, _utils.removeTrailingZeros)(item[0]));
                    focusInputElement(triggerPriceInputRef.current);
                }
            } else {
                if (formattedOrder.order_type === _types.OrderType.STOP_LIMIT || formattedOrder.order_type === _types.OrderType.LIMIT) {
                    props.onFieldChange("order_price", (0, _utils.removeTrailingZeros)(item[0]));
                    focusInputElement(priceInputRef.current);
                } else {
                    // other order type
                    let newType;
                    if (formattedOrder.order_type === _types.OrderType.STOP_MARKET) {
                        newType = _types.OrderType.STOP_LIMIT;
                    } else if (formattedOrder.order_type === _types.OrderType.MARKET) {
                        newType = _types.OrderType.LIMIT;
                    }
                    if (typeof newType !== "undefined") {
                        props.onFieldChange("order_type", newType);
                    }
                    props.onFieldChange("order_price", (0, _utils.removeTrailingZeros)(item[0]));
                    focusInputElement(priceInputRef.current);
                }
            }
            // if (formattedOrder.order_type === OrderType.STOP_LIMIT) {
            //   if (currentFocusInput.current === InputType.TRIGGER_PRICE) {
            //     // newType = OrderType.LIMIT;
            //     props.onFieldChange("trigger_price", item[0].toString());
            //     focusInputElement(triggerPriceInputRef.current);
            //   } else {
            //     props.onFieldChange("order_price", item[0].toString());
            //     focusInputElement(priceInputRef.current);
            //   }
            // } else {
            //   let newType;
            //   // if (formattedOrder.order_type === OrderType.STOP_MARKET) {
            //   //   newType = OrderType.STOP_LIMIT;
            //   // } else if (formattedOrder.order_type === OrderType.MARKET) {
            //   //   newType = OrderType.LIMIT;
            //   // }
            //   if (typeof newType !== "undefined") {
            //     props.onFieldChange("order_type", newType);
            //   }
            //   props.onFieldChange("order_price", item[0].toString());
            //   focusInputElement(priceInputRef.current);
            // }
            function focusInputElement(target) {
                setTimeout(()=>{
                    target?.focus();
                }, 0);
            }
        };
        ee.on("orderbook:item:click", orderbookItemClickHandler);
        return ()=>{
            ee.off("orderbook:item:click", orderbookItemClickHandler);
        };
    }, [
        formattedOrder.order_type
    ]);
    const [buttonText, setButtonText] = (0, _react.useState)("Buy / Long");
    // const isTable = useMediaQuery(MEDIA_TABLET);
    const formatQty = ()=>{
        // const dp = new Decimal(symbolConfig?.base_tick || "0").toNumber();
        // TODO: optimization
        // if (dp < 1) return;
        const quantity = _hooks.utils.formatNumber(formattedOrder?.order_quantity, new _utils.Decimal(symbolConfig?.base_tick || "0").toNumber());
        props.onFieldChange("order_quantity", quantity);
    };
    const onFocus = (type)=>(_)=>{
            currentFocusInput.current = type;
        };
    const onBlur = (type)=>(_)=>{
            setTimeout(()=>{
                if (currentFocusInput.current !== type) return;
                currentFocusInput.current = 4;
            }, 300);
            if (type === 2) {
                formatQty();
            }
        };
    const onSubmit = (event)=>{
        //
        event.preventDefault();
        if (!symbolConfig) {
            return Promise.reject("symbolConfig is null");
        }
        return Promise.resolve().then(()=>{
            if (metaState.errors?.order_price?.message || metaState.errors?.order_quantity?.message || metaState.errors?.trigger_price?.message || metaState.errors?.total?.message) {
                setErrorsVisible(true);
                return Promise.reject("cancel");
            }
            formatQty();
            if (needConfirm) {
                return _modal.modal.confirm({
                    maxWidth: "sm",
                    title: "Confirm Order",
                    okId: "orderly-confirm-order-dialog-confirm",
                    cancelId: "orderly-confirm-order-dialog-cancel",
                    onCancel: ()=>{
                        return Promise.reject("cancel");
                    },
                    footer: !isTablet ? /*#__PURE__*/ (0, _jsxruntime.jsx)(_orderConfirmViewnew.OrderConfirmFooter, {
                        onCancel: ()=>{
                            return Promise.reject("cancel");
                        }
                    }) : undefined,
                    content: /*#__PURE__*/ (0, _jsxruntime.jsx)(_orderConfirmViewnew.OrderConfirmView, {
                        order: {
                            ...formattedOrder,
                            side: side,
                            symbol: props.symbol
                        },
                        symbol: symbol,
                        base: symbolConfig?.base,
                        quote: symbolConfig?.quote,
                        isTable: isTablet
                    })
                });
            } else {
                return Promise.resolve(true);
            }
        }).then((isOk)=>{
            return props.submit().then((res)=>{
            // props.setValues({
            //   trigger_price: "",
            //   order_price: "",
            //   order_quantity: "",
            //   total: "",
            // });
            // resetForm?.();
            }, (err)=>{
                if (typeof err === "string") {
                    _toast.toast.error(err);
                } else if (err.name === "ApiError") {
                    _toast.toast.error(err.message);
                } else {
                    ;
                    _toast.toast.error(err?.message);
                }
            });
        }).catch((error)=>{
            if (error !== "cancel" && !!error?.message) {
                _toast.toast.error(error.message || "Failed");
            }
        });
    };
    const onDeposit = (0, _react.useCallback)((event)=>{
        event.preventDefault();
        props.onDeposit?.();
    }, []);
    (0, _react.useEffect)(()=>{
        if (side === _types.OrderSide.BUY) {
            setButtonText("Buy / Long");
        } else {
            setButtonText("Sell / Short");
        }
    // methods.setValue("side", side);
    // methods.clearErrors();
    }, [
        side
    ]);
    //
    const totalAmount = (0, _react.useMemo)(()=>{
        const quantity = formattedOrder.order_quantity;
        const type = formattedOrder.order_type;
        if (!markPrice || type !== _types.OrderType.MARKET && type !== _types.OrderType.STOP_MARKET || currentFocusInput.current === 3 || !quantity) {
            return formattedOrder.total;
        }
        return new _utils.Decimal(quantity).mul(markPrice).todp(2).toString();
    }, [
        markPrice,
        formattedOrder.total,
        formattedOrder.order_quantity,
        formattedOrder.order_type
    ]);
    (0, _react.useEffect)(()=>{
        function handleClick() {
            // When the user clicks outside the form area, hide the error message
            if (!isClickForm.current) {
                setErrorsVisible(false);
            }
            isClickForm.current = false;
        }
        document.body.addEventListener("click", handleClick);
        return ()=>{
            document.body.removeEventListener("click", handleClick);
        };
    }, []);
    return(// @ts-ignore
    /*#__PURE__*/ (0, _jsxruntime.jsx)("form", {
        onSubmit: onSubmit,
        onClick: ()=>{
            isClickForm.current = true;
        },
        id: "orderly-order-entry-form",
        children: /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
            className: "orderly-flex orderly-flex-col orderly-gap-3 orderly-text-3xs",
            children: [
                /*#__PURE__*/ (0, _jsxruntime.jsx)(SegmentedButton, {
                    id: "orderly-order-entry-trade-type",
                    buttons: [
                        {
                            id: "orderly-order-entry-buy-button",
                            label: "Buy",
                            value: _types.OrderSide.BUY,
                            disabled,
                            activeClassName: "orderly-bg-trade-profit orderly-text-base-contrast after:orderly-bg-trade-profit orderly-font-bold desktop:orderly-font-bold",
                            disabledClassName: "orderly-bg-base-400 orderly-text-base-contrast-20 after:orderly-bg-base-400 orderly-cursor-not-allowed orderly-font-bold desktop:orderly-font-bold"
                        },
                        {
                            id: "orderly-order-entry-sell-button",
                            label: "Sell",
                            value: _types.OrderSide.SELL,
                            disabled,
                            activeClassName: "orderly-bg-trade-loss orderly-text-base-contrast after:orderly-bg-trade-loss orderly-font-bold desktop:orderly-font-bold",
                            disabledClassName: "orderly-bg-base-400 orderly-text-base-contrast-20 after:orderly-bg-base-400 orderly-cursor-not-allowed orderly-font-bold desktop:orderly-font-bold"
                        }
                    ],
                    onChange: (value)=>{
                        // onSideChange?.(value as OrderSide);
                        setErrorsVisible(false);
                        props.onFieldChange("side", value);
                    },
                    value: side
                }),
                /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
                    className: "orderly-flex orderly-justify-between orderly-items-center",
                    children: [
                        /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
                            className: "orderly-flex orderly-gap-1 orderly-text-base-contrast-54 orderly-text-4xs desktop:orderly-text-3xs",
                            children: [
                                /*#__PURE__*/ (0, _jsxruntime.jsx)(_freeCollat.FreeCollat, {}),
                                /*#__PURE__*/ (0, _jsxruntime.jsx)(_text.Numeral, {
                                    rule: "price",
                                    className: "orderly-text-base-contrast-80",
                                    precision: 0,
                                    children: `${freeCollateral ?? "--"}`
                                }),
                                !isTablet && /*#__PURE__*/ (0, _jsxruntime.jsx)("span", {
                                    className: "orderly-text-base-contrast-36",
                                    children: "USDC"
                                })
                            ]
                        }),
                        /*#__PURE__*/ (0, _jsxruntime.jsx)(_button.default, {
                            id: "orderly-order-entry-deposit-button",
                            variant: "text",
                            size: "small",
                            type: "button",
                            onClick: onDeposit,
                            className: "orderly-text-link orderly-text-4xs",
                            children: "Deposit"
                        })
                    ]
                }),
                /*#__PURE__*/ (0, _jsxruntime.jsx)(_mSelect.MSelect, {
                    id: "orderly-order-entry-order-type",
                    label: "Order Type",
                    value: formattedOrder.order_type,
                    className: "orderly-bg-base-600 orderly-font-semibold",
                    color: side === _types.OrderSide.BUY ? "buy" : "sell",
                    fullWidth: true,
                    options: [
                        {
                            label: "Limit order",
                            value: "LIMIT",
                            id: "orderly-order-entry-order-type-limit"
                        },
                        {
                            label: "Market order",
                            value: "MARKET",
                            id: "orderly-order-entry-order-type-market"
                        },
                        {
                            label: "Stop limit",
                            value: "STOP_LIMIT",
                            id: "orderly-order-entry-order-type-stop-limit"
                        },
                        {
                            label: "Stop market",
                            value: "STOP_MARKET",
                            id: "orderly-order-entry-order-type-stop-market"
                        }
                    ],
                    onChange: (value)=>{
                        // field.onChange(value);
                        // methods.setValue("order_price", "", {
                        //   shouldValidate: false,
                        // });
                        // methods.clearErrors();
                        props.onFieldChange("order_type", value);
                    }
                }),
                isStopOrder && /*#__PURE__*/ (0, _jsxruntime.jsx)(_input.Input, {
                    disabled: disabled,
                    ref: triggerPriceInputRef,
                    prefix: "Trigger",
                    suffix: symbolConfig?.quote,
                    type: "text",
                    inputMode: "decimal",
                    id: "order_trigger_price_input",
                    name: "order_trigger_price_input",
                    autoComplete: "off",
                    error: !!metaState.errors?.trigger_price && errorsVisible,
                    helpText: metaState.errors?.trigger_price?.message,
                    className: "orderly-text-right orderly-font-semibold",
                    value: (0, _utils.commify)(formattedOrder.trigger_price || ""),
                    containerClassName: "orderly-bg-base-600",
                    onChange: (event)=>{
                        // field.onChange(event.target.value);
                        props.onFieldChange("trigger_price", event.target.value);
                    },
                    onFocus: onFocus(1),
                    onBlur: onBlur(1)
                }),
                /*#__PURE__*/ (0, _jsxruntime.jsx)(_input.Input, {
                    disabled: disabled,
                    ref: priceInputRef,
                    prefix: "Price",
                    suffix: symbolConfig?.quote,
                    type: "text",
                    inputMode: "decimal",
                    id: "order_price_input",
                    name: "order_price_input",
                    error: !!metaState.errors?.order_price && errorsVisible,
                    helpText: metaState.errors?.order_price?.message,
                    className: "orderly-text-right orderly-font-semibold",
                    autoComplete: "off",
                    value: isMarketOrder ? "Market" : (0, _utils.commify)(formattedOrder.order_price || ""),
                    containerClassName: isMarketOrder ? "orderly-bg-base-700" : "orderly-bg-base-600",
                    readOnly: isMarketOrder,
                    onChange: (event)=>{
                        // field.onChange(event.target.value);
                        props.onFieldChange("order_price", event.target.value);
                    },
                    onFocus: onFocus(0),
                    onBlur: onBlur(0)
                }),
                /*#__PURE__*/ (0, _jsxruntime.jsx)(_input.Input, {
                    disabled: disabled,
                    prefix: "Quantity",
                    type: "text",
                    inputMode: "decimal",
                    suffix: symbolConfig?.base,
                    id: "order_quantity_input",
                    name: "order_quantity_input",
                    className: "orderly-text-right",
                    containerClassName: "orderly-bg-base-600",
                    error: !!metaState.errors?.order_quantity && errorsVisible,
                    helpText: metaState.errors?.order_quantity?.message,
                    autoComplete: "off",
                    value: (0, _utils.commify)(formattedOrder.order_quantity || ""),
                    onChange: (event)=>{
                        props.onFieldChange("order_quantity", event.target.value);
                    },
                    onFocus: onFocus(2),
                    onBlur: onBlur(2)
                }),
                /*#__PURE__*/ (0, _jsxruntime.jsx)(_slider.Slider, {
                    id: "orderly-order-entry-slider",
                    color: side === _types.OrderSide.BUY ? "buy" : "sell",
                    markLabelVisible: false,
                    min: 0,
                    max: maxQty === 0 ? 1 : maxQty,
                    markCount: 4,
                    disabled: maxQty === 0,
                    step: symbolConfig?.["base_tick"],
                    value: [
                        Number(formattedOrder.order_quantity ?? 0)
                    ],
                    onValueChange: (value)=>{
                        //
                        if (typeof value[0] !== "undefined") {
                            props.onFieldChange("order_quantity", value[0]);
                        }
                    }
                }),
                /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
                    className: (0, _css.cn)("orderly-hidden desktop:!orderly-flex orderly-justify-between -orderly-mt-2", {
                        "orderly-text-trade-profit": side === _types.OrderSide.BUY,
                        "orderly-text-trade-loss": side === _types.OrderSide.SELL
                    }),
                    children: [
                        /*#__PURE__*/ (0, _jsxruntime.jsxs)("span", {
                            children: [
                                Number((0, _utils1.convertValueToPercentage)(Number(formattedOrder.order_quantity ?? 0), 0, maxQty).toFixed()),
                                "%"
                            ]
                        }),
                        /*#__PURE__*/ (0, _jsxruntime.jsxs)("button", {
                            id: "orderly-order-entry-max-buy-or-sell",
                            type: "button",
                            className: "orderly-flex orderly-items-center orderly-gap-1 orderly-tabular-nums",
                            onClick: ()=>{
                                props.onFieldChange("order_quantity", maxQty);
                            },
                            children: [
                                /*#__PURE__*/ (0, _jsxruntime.jsx)("span", {
                                    id: "orderly-order-entry-max-buy-or-sell-text",
                                    className: "orderly-text-base-contrast-54",
                                    children: formattedOrder.side === _types.OrderSide.BUY ? "Max buy" : "Max sell"
                                }),
                                /*#__PURE__*/ (0, _jsxruntime.jsx)(_text.Numeral, {
                                    precision: baseDP,
                                    children: maxQty
                                })
                            ]
                        })
                    ]
                }),
                /*#__PURE__*/ (0, _jsxruntime.jsx)(_input.Input, {
                    disabled: disabled,
                    className: "orderly-text-right",
                    containerClassName: "orderly-bg-base-600",
                    prefix: "Total ≈",
                    suffix: symbolConfig?.quote,
                    type: "text",
                    inputMode: "decimal",
                    id: "order_total_input",
                    name: "order_total_input",
                    autoComplete: "off",
                    autoFocus: false,
                    error: !!metaState.errors?.total && errorsVisible,
                    helpText: metaState.errors?.total?.message,
                    value: (0, _utils.commify)(currentFocusInput.current === 3 ? formattedOrder.total : totalAmount),
                    onFocus: onFocus(3),
                    onBlur: onBlur(3),
                    onChange: (event)=>{
                        // field.onChange(event.target.value);
                        props.onFieldChange("total", event.target.value);
                    }
                }),
                !isTablet && /*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, {
                    children: [
                        /*#__PURE__*/ (0, _jsxruntime.jsx)(_divider.Divider, {}),
                        /*#__PURE__*/ (0, _jsxruntime.jsx)(_setInfo.EstInfo, {
                            estLiqPrice: props.estLiqPrice,
                            precision: symbolConfig?.quote_dp,
                            estLeverage: props.estLeverage
                        })
                    ]
                }),
                /*#__PURE__*/ (0, _jsxruntime.jsx)(_divider.Divider, {}),
                /*#__PURE__*/ (0, _jsxruntime.jsx)(_orderOptions.OrderOptions, {
                    formattedOrder: formattedOrder,
                    showConfirm: needConfirm,
                    onConfirmChange: setNeedConfirm,
                    onReduceOnlyChange: (value)=>props.onFieldChange("reduce_only", value),
                    reduceOnly: formattedOrder.reduce_only,
                    onFieldChange: props.onFieldChange
                }),
                /*#__PURE__*/ (0, _jsxruntime.jsx)(_accountStatus.StatusGuardButton, {
                    id: "orderly-order-entry-status-guard-button",
                    children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_button.default, {
                        id: "orderly-order-entry-confirm-button",
                        className: "orderly-text-xs desktop:orderly-font-bold desktop:orderly-text-sm",
                        type: "submit",
                        loading: props.submitting,
                        color: side === _types.OrderSide.BUY ? "buy" : "sell",
                        fullWidth: true,
                        children: buttonText
                    })
                })
            ]
        })
    }));
});

//# sourceMappingURL=index.js.map