"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "OrderQuantity", {
    enumerable: true,
    get: function() {
        return OrderQuantity;
    }
});
const _jsxruntime = require("react/jsx-runtime");
const _react = require("react");
const _types = require("@orderly.network/types");
const _lucidereact = require("lucide-react");
const _css = require("../../../utils/css");
const _popover = require("../../../popover");
const _utils = require("@orderly.network/utils");
const _symbolProvider = require("../../../provider/symbolProvider");
const _button = /*#__PURE__*/ _interop_require_default(require("../../../button"));
const _orderListContext = require("../shared/orderListContext");
const _toast = require("../../../toast");
const _divider = require("../../../divider");
const _hooks = require("@orderly.network/hooks");
const _input = require("../../../input");
const _tpslOrderRowContext = require("../../../block/tp_sl/tpslOrderRowContext");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
const OrderQuantity = (props)=>{
    const { order } = props;
    const [quantity, setQuantity] = (0, _react.useState)(order.quantity.toString());
    // const { editOrder } = useContext(OrderListContext);
    const [open, setOpen] = (0, _react.useState)(0);
    const [editting, setEditting] = (0, _react.useState)(false);
    (0, _react.useEffect)(()=>{
        setQuantity(order.quantity.toString());
    }, [
        props.order.quantity
    ]);
    if (!editting && open <= 0) {
        return /*#__PURE__*/ (0, _jsxruntime.jsx)(NormalState, {
            order: order,
            quantity: quantity,
            setEditing: setEditting
        });
    }
    return /*#__PURE__*/ (0, _jsxruntime.jsx)(EditingState, {
        order: order,
        quantity: quantity,
        setQuantity: setQuantity,
        editting: editting,
        setEditting: setEditting,
        open: open,
        setOpen: setOpen
    });
};
const NormalState = (props)=>{
    const { order, quantity } = props;
    const executed = order.total_executed_quantity;
    return /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
        className: (0, _css.cn)("orderly-flex orderly-max-w-[110px] orderly-justify-start orderly-items-center orderly-gap-1 orderly-relative orderly-font-semibold", {
            "orderly-text-trade-profit": order.side === _types.OrderSide.BUY,
            "orderly-text-trade-loss": order.side === _types.OrderSide.SELL
        }),
        onClick: (e)=>{
            e.stopPropagation();
            e.preventDefault();
            props.setEditing(true);
        },
        children: [
            "algo_type" in order && order.algo_type === _types.AlgoOrderRootType.TP_SL ? null : /*#__PURE__*/ (0, _jsxruntime.jsxs)(_jsxruntime.Fragment, {
                children: [
                    /*#__PURE__*/ (0, _jsxruntime.jsx)("span", {
                        children: executed
                    }),
                    /*#__PURE__*/ (0, _jsxruntime.jsx)("span", {
                        children: "/"
                    })
                ]
            }),
            /*#__PURE__*/ (0, _jsxruntime.jsx)("div", {
                className: "orderly-px-2 orderly-flex orderly-min-w-[70px] orderly-items-center orderly-h-[28px] orderly-bg-base-700 orderly-text-2xs orderly-font-semibold orderly-rounded-lg",
                children: quantity
            })
        ]
    });
};
const EditingState = (props)=>{
    const { order, quantity, setQuantity: originSetQuantity, editting, setEditting, setOpen, open } = props;
    const [error, setError] = (0, _react.useState)();
    const { editOrder, editAlgoOrder, checkMinNotional } = (0, _react.useContext)(_orderListContext.OrderListContext);
    const { onUpdateOrder: onUpdateTPSLOrder, position } = (0, _tpslOrderRowContext.useTPSLOrderRowContext)();
    const setQuantity = (qty)=>{
        originSetQuantity(qty);
        const positionQty = Math.abs(position?.position_qty || 0);
        if (position && Number(qty) > positionQty) {
            setError(`Quantity should be less than position quantity : ${positionQty}`);
        } else {
            setError(undefined);
        }
    };
    const closePopover = ()=>setOpen(0);
    const cancelPopover = ()=>{
        setOpen(-1);
        setQuantity(order.quantity.toString());
    };
    const boxRef = (0, _react.useRef)(null);
    const confirmRef = (0, _react.useRef)(null);
    const { base } = (0, _symbolProvider.useSymbolContext)();
    const [isSubmitting, setIsSubmitting] = (0, _react.useState)(false);
    const inputRef = (0, _react.useRef)(null);
    (0, _react.useEffect)(()=>{
        const docClickHandler = (event)=>{
            // close the input when click outside of boxRef
            const el = boxRef?.current;
            if (!el || el.contains(event.target)) {
                return;
            }
            const el2 = confirmRef?.current;
            if (!el2 || el2.contains(event.target)) {
                return;
            }
            setQuantity(order.quantity.toString());
            setEditting(false);
        };
        document.body.addEventListener("click", docClickHandler);
        return ()=>{
            document.body.removeEventListener("click", docClickHandler);
        };
    }, []);
    const clickHandler = ()=>{
        if (!!error) {
            return;
        }
        setEditting(false);
        if (Number(quantity) === Number(order.quantity)) {
            return;
        }
        const price = order.algo_order_id !== undefined ? order.trigger_price : order.price;
        if (price !== null && order.reduce_only !== true) {
            const notionalText = checkMinNotional(order.symbol, price, quantity);
            if (notionalText) {
                _toast.toast.error(notionalText);
                setIsSubmitting(false);
                cancelPopover();
                return;
            }
        }
        setOpen(1);
    };
    const onClick = (event)=>{
        event.stopPropagation();
        event.preventDefault();
        clickHandler();
    };
    const handleKeyDown = (event)=>{
        if (event.key === "Enter") {
            event.stopPropagation();
            event.preventDefault();
            clickHandler();
        }
    };
    const onConfirm = (0, _react.useCallback)(()=>{
        setIsSubmitting(true);
        let params = {
            symbol: order.symbol,
            order_type: order.type,
            side: order.side,
            order_price: order.price,
            order_quantity: quantity,
            // reduce_only: Boolean(order.reduce_only),
            algo_order_id: order.algo_order_id
        };
        if (typeof params.algo_order_id !== "undefined" && params.order_type === "MARKET") {
            // stop market order
            const { order_price, ...rest } = params;
            params = rest;
        }
        if (typeof order.reduce_only !== "undefined") {
            params.reduce_only = order.reduce_only;
        }
        if (order.order_tag !== undefined) {
            params = {
                ...params,
                order_tag: order.order_tag
            };
        }
        // @ts-ignore
        if (order.visible_quantity === 0) {
            params["visible_quantity"] = 0;
        }
        // @ts-ignore
        if (order.tag !== undefined) {
            // @ts-ignore
            params["order_tag"] = order.tag;
        }
        let future;
        if ("algo_type" in order && order.algo_type === _types.AlgoOrderRootType.TP_SL) {
            future = onUpdateTPSLOrder(order, params);
        } else {
            if (order.algo_order_id !== undefined) {
                future = editAlgoOrder(order.algo_order_id.toString(), params);
            } else {
                future = editOrder(order.order_id.toString(), params);
            }
        }
        // @ts-ignore
        future.then((result)=>{
            closePopover();
            setQuantity(quantity.toString());
        // setTimeout(() => inputRef.current?.blur(), 300);
        }, (err)=>{
            _toast.toast.error(err.message);
            setQuantity(order.quantity.toString());
            cancelPopover();
        }).finally(()=>setIsSubmitting(false));
    }, [
        quantity
    ]);
    return /*#__PURE__*/ (0, _jsxruntime.jsx)(_popover.Popover, {
        open: open > 0,
        onOpenChange: (open)=>setOpen(open ? 1 : 0),
        children: /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
            className: (0, _css.cn)("orderly-flex orderly-min-w-[70px] orderly-justify-start orderly-items-center orderly-relative orderly-font-semibold", {
                "orderly-text-trade-profit": order.side === _types.OrderSide.BUY,
                "orderly-text-trade-loss": order.side === _types.OrderSide.SELL
            }),
            ref: boxRef,
            children: [
                /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
                    className: (0, _css.cn)("orderly-absolute orderly-left-1 orderly-flex", {
                        "orderly-animate-in orderly-fade-in orderly-zoom-in": editting,
                        "orderly-animate-out orderly-fade-out orderly-zoom-out  orderly-hidden": !editting
                    }),
                    children: [
                        /*#__PURE__*/ (0, _jsxruntime.jsx)("button", {
                            className: "hover:orderly-bg-base-contrast/10 orderly-h-[25px] orderly-rounded orderly-px-1 orderly-text-base-contrast-54 hover:orderly-text-base-contrast-80",
                            // @ts-ignore
                            onClick: (e)=>{
                                e.stopPropagation();
                                e.preventDefault();
                                setEditting(false);
                                setQuantity(order.quantity.toString());
                            },
                            children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_lucidereact.X, {
                                size: 14
                            })
                        }),
                        /*#__PURE__*/ (0, _jsxruntime.jsx)(_divider.Divider, {
                            vertical: true,
                            className: "orderly-ml-[1px] before:orderly-h-[16px] orderly-min-w-[2px]"
                        })
                    ]
                }),
                /*#__PURE__*/ (0, _jsxruntime.jsx)(_popover.PopoverAnchor, {
                    asChild: true,
                    children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_input.Input, {
                        ref: inputRef,
                        type: "text",
                        value: (0, _utils.commify)(quantity),
                        onChange: (e)=>setQuantity((0, _hooks.cleanStringStyle)(e.target.value)),
                        onFocus: ()=>setEditting(true),
                        onBlur: ()=>{
                            setTimeout(()=>{
                                setEditting(false);
                                if (open <= 0) {
                                    setQuantity(order.quantity.toString());
                                }
                            }, 100);
                        },
                        error: !!error,
                        helpText: error,
                        onKeyDown: handleKeyDown,
                        autoFocus: true,
                        containerClassName: "orderly-h-auto orderly-pl-7 orderly-flex-1",
                        className: "orderly-flex-1 orderly-pl-9 orderly-pr-9 orderly-bg-base-700 orderly-px-2 orderly-py-1 orderly-rounded"
                    })
                }),
                /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
                    className: (0, _css.cn)("orderly-absolute orderly-right-1 orderly-flex", {
                        "orderly-animate-in orderly-fade-in orderly-zoom-in": editting,
                        "orderly-animate-out orderly-fade-out orderly-zoom-out  orderly-hidden": !editting
                    }),
                    children: [
                        /*#__PURE__*/ (0, _jsxruntime.jsx)(_divider.Divider, {
                            vertical: true,
                            className: "before:orderly-h-[16px] orderly-min-w-[2px] orderly-mr-[1px]"
                        }),
                        /*#__PURE__*/ (0, _jsxruntime.jsx)("button", {
                            className: "hover:orderly-bg-base-contrast/10 orderly-h-[25px] orderly-rounded orderly-px-1 orderly-text-base-contrast-54 hover:orderly-text-base-contrast-80",
                            // @ts-ignore
                            onMouseDown: onClick,
                            children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_lucidereact.Check, {
                                size: 14
                            })
                        }),
                        /*#__PURE__*/ (0, _jsxruntime.jsx)(_popover.PopoverContent, {
                            align: "end",
                            side: "top",
                            className: "orderly-w-[340px]",
                            onCloseAutoFocus: (e)=>{
                                if (inputRef.current && open === -1) {
                                    inputRef.current.focus();
                                }
                            },
                            onOpenAutoFocus: (e)=>e.preventDefault(),
                            children: /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
                                className: "orderly-pt-5 orderly-relative",
                                children: [
                                    /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
                                        className: "orderly-text-base-contrast-54 orderly-text-2xs desktop:orderly-text-sm",
                                        children: [
                                            "You agree changing the quantity of ",
                                            base,
                                            "-PERP order to",
                                            " ",
                                            /*#__PURE__*/ (0, _jsxruntime.jsx)("span", {
                                                className: "orderly-text-warning",
                                                children: (0, _utils.commify)(quantity)
                                            }),
                                            "."
                                        ]
                                    }),
                                    /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
                                        className: "orderly-grid orderly-grid-cols-2 orderly-gap-2 orderly-mt-5",
                                        children: [
                                            /*#__PURE__*/ (0, _jsxruntime.jsx)(_button.default, {
                                                color: "tertiary",
                                                onClick: cancelPopover,
                                                disabled: isSubmitting,
                                                children: "Cancel"
                                            }),
                                            /*#__PURE__*/ (0, _jsxruntime.jsx)(_button.default, {
                                                // @ts-ignore
                                                ref: confirmRef,
                                                loading: isSubmitting,
                                                onClick: onConfirm,
                                                children: "Confirm"
                                            })
                                        ]
                                    }),
                                    /*#__PURE__*/ (0, _jsxruntime.jsx)("button", {
                                        className: "orderly-absolute orderly-right-0 orderly-top-0 orderly-text-base-contrast-54",
                                        onClick: cancelPopover,
                                        children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_lucidereact.X, {
                                            size: 18
                                        })
                                    })
                                ]
                            })
                        })
                    ]
                })
            ]
        })
    });
};

//# sourceMappingURL=quantity.js.map