"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "Price", {
    enumerable: true,
    get: function() {
        return Price;
    }
});
const _jsxruntime = require("react/jsx-runtime");
const _button = /*#__PURE__*/ _interop_require_default(require("../../../button"));
const _popover = require("../../../popover");
const _symbolProvider = require("../../../provider/symbolProvider");
const _css = require("../../../utils/css");
const _utils = require("@orderly.network/utils");
const _lucidereact = require("lucide-react");
const _react = require("react");
const _orderListContext = require("../shared/orderListContext");
const _toast = require("../../../toast");
const _hooks = require("@orderly.network/hooks");
const _reacttooltip = require("@radix-ui/react-tooltip");
const _divider = require("../../../divider");
const _input = require("../../../input");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
const Price = (props)=>{
    const { order } = props;
    const [price, setPrice] = (0, _react.useState)(order.price?.toString() ?? "Market");
    const [open, setOpen] = (0, _react.useState)(0);
    const [editting, setEditting] = (0, _react.useState)(false);
    (0, _react.useEffect)(()=>{
        {
            if (!!props.order.price) {
                setPrice(`${props.order.price}`);
            }
        }
    }, [
        props.order.price
    ]);
    const isAlgoMarketOrder = order.algo_order_id && order.type == "MARKET";
    if (isAlgoMarketOrder) {
        return /*#__PURE__*/ (0, _jsxruntime.jsx)("span", {
            children: "Market"
        });
    }
    if (!editting && open <= 0) {
        return /*#__PURE__*/ (0, _jsxruntime.jsx)(NormalState, {
            order: order,
            price: price,
            setEditing: setEditting
        });
    }
    return /*#__PURE__*/ (0, _jsxruntime.jsx)(EditingState, {
        order: order,
        price: price,
        setPrice: setPrice,
        editting: editting,
        setEditting: setEditting,
        open: open,
        setOpen: setOpen
    });
};
const NormalState = (props)=>{
    const { order, price } = props;
    return /*#__PURE__*/ (0, _jsxruntime.jsx)("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"),
        onClick: (e)=>{
            e.stopPropagation();
            e.preventDefault();
            props.setEditing(true);
        },
        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: price
        })
    });
};
const EditingState = (props)=>{
    const { order, price, setPrice, editting, setEditting, setOpen, open } = props;
    const isAlgoOrder = order?.algo_order_id !== undefined;
    // console.log("price node", order);
    const isStopMarket = order?.type === "MARKET" && isAlgoOrder;
    const [isSubmitting, setIsSubmitting] = (0, _react.useState)(false);
    const { editOrder, editAlgoOrder, checkMinNotional } = (0, _react.useContext)(_orderListContext.OrderListContext);
    const boxRef = (0, _react.useRef)(null);
    const confirmRef = (0, _react.useRef)(null);
    const { base, base_dp } = (0, _symbolProvider.useSymbolContext)();
    const closePopover = ()=>setOpen(0);
    const cancelPopover = ()=>{
        setOpen(-1);
        setPrice(order.price?.toString() ?? "Market");
    };
    (0, _react.useEffect)(()=>{
        const clickHandler = (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;
            }
            setPrice(order.price?.toString() ?? "Market");
            setEditting(false);
        };
        document.body.addEventListener("click", clickHandler);
        return ()=>{
            document.body.removeEventListener("click", clickHandler);
        };
    }, []);
    const onClick = ()=>{
        // event.stopPropagation();
        // event.preventDefault();
        setEditting(false);
        if (Number(price) === Number(order.price)) {
            return;
        }
        if (order.reduce_only !== true) {
            const notionalText = checkMinNotional(order.symbol, price, order.quantity);
            if (notionalText) {
                _toast.toast.error(notionalText);
                setIsSubmitting(false);
                cancelPopover();
                return;
            }
        }
        setOpen(1);
    };
    const onClickCancel = (order)=>{
        setPrice(order.price);
        setEditting(false);
    };
    const handleKeyDown = (event)=>{
        if (event.key === "Enter") {
            event.stopPropagation();
            event.preventDefault();
            onClick();
        }
    };
    const onConfirm = ()=>{
        setIsSubmitting(true);
        let order_id = order.order_id;
        let data = {
            order_price: price,
            order_quantity: order.quantity,
            symbol: order.symbol,
            order_type: order.type,
            side: order.side
        };
        if (typeof order.reduce_only !== "undefined") {
            data.reduce_only = order.reduce_only;
        }
        if (order.order_tag !== undefined) {
            data = {
                ...data,
                order_tag: order.order_tag
            };
        }
        if (isAlgoOrder) {
            order_id = order.algo_order_id;
            data = {
                ...data,
                order_id,
                price: price,
                algo_order_id: order_id
            };
        }
        // @ts-ignore
        if (order.visible_quantity === 0) {
            data["visible_quantity"] = 0;
        }
        // @ts-ignore
        if (order.tag !== undefined) {
            // @ts-ignore
            data["order_tag"] = order.tag;
        }
        let future;
        if (order.algo_order_id !== undefined) {
            future = editAlgoOrder(order.algo_order_id.toString(), data);
        } else {
            future = editOrder(order.order_id.toString(), data);
        }
        // @ts-ignore
        future.then((result)=>{
            closePopover();
            setPrice(price);
        // setTimeout(() => inputRef.current?.blur(), 300);
        }, (err)=>{
            _toast.toast.error(err.message);
            // @ts-ignore
            setPrice(order.price?.toString());
            cancelPopover();
        }).finally(()=>setIsSubmitting(false));
    };
    const inputRef = (0, _react.useRef)(null);
    // @ts-ignore
    const rangeInfo = (0, _hooks.useSymbolPriceRange)(order.symbol, // @ts-ignore
    order.side, isAlgoOrder ? order.trigger_price : undefined);
    const hintInfo = (0, _react.useMemo)(()=>{
        if (!rangeInfo) return "";
        if (isStopMarket) return "";
        if (!editting) return "";
        if (Number(price) > rangeInfo.max) {
            return `Price can not be greater than ${rangeInfo.max} USDC.`;
        }
        if (Number(price) < rangeInfo.min) {
            return `Price can not be less than ${rangeInfo.min} USDC.`;
        }
        return "";
    }, [
        isStopMarket,
        editting,
        rangeInfo,
        price
    ]);
    return /*#__PURE__*/ (0, _jsxruntime.jsx)(_popover.Popover, {
        open: open > 0,
        onOpenChange: (open)=>setOpen(open ? 1 : 0),
        children: /*#__PURE__*/ (0, _jsxruntime.jsxs)("div", {
            className: "orderly-flex orderly-justify-start orderly-items-center orderly-gap-1 orderly-relative orderly-font-semibold",
            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",
                            onClick: ()=>onClickCancel(order),
                            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.jsxs)(_popover.PopoverAnchor, {
                    children: [
                        isStopMarket && /*#__PURE__*/ (0, _jsxruntime.jsx)("span", {
                            children: "Market"
                        }),
                        !isStopMarket && /*#__PURE__*/ (0, _jsxruntime.jsxs)(_reacttooltip.Tooltip, {
                            open: hintInfo.length > 0,
                            children: [
                                /*#__PURE__*/ (0, _jsxruntime.jsx)(_reacttooltip.TooltipTrigger, {
                                    asChild: true,
                                    children: /*#__PURE__*/ (0, _jsxruntime.jsx)(_input.Input, {
                                        ref: inputRef,
                                        type: "text",
                                        value: (0, _utils.commify)(price),
                                        onChange: (e)=>setPrice((0, _hooks.cleanStringStyle)(e.target.value)),
                                        onFocus: ()=>setEditting(true),
                                        onBlur: ()=>{
                                            setTimeout(()=>{
                                                setEditting(false);
                                                if (open <= 0) {
                                                    setPrice(order.price?.toString() ?? "Market");
                                                }
                                            }, 100);
                                        },
                                        onKeyDown: handleKeyDown,
                                        autoFocus: true,
                                        containerClassName: "orderly-h-auto orderly-pl-7",
                                        className: "orderly-w-full 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)(_reacttooltip.TooltipContent, {
                                    className: "orderly-max-w-[270px] orderly-rounded-lg orderly-bg-base-400 orderly-p-3 orderly-z-50",
                                    align: "center",
                                    children: [
                                        hintInfo,
                                        /*#__PURE__*/ (0, _jsxruntime.jsx)(_reacttooltip.TooltipArrow, {
                                            width: 10,
                                            height: 7,
                                            className: "orderly-fill-base-400"
                                        })
                                    ]
                                })
                            ]
                        })
                    ]
                }),
                /*#__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 price of ",
                                            base,
                                            "-PERP order to",
                                            " ",
                                            /*#__PURE__*/ (0, _jsxruntime.jsx)("span", {
                                                className: "orderly-text-warning",
                                                children: (0, _utils.commify)(price)
                                            }),
                                            "."
                                        ]
                                    }),
                                    /*#__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, {
                                                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=price.js.map