import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import Button from "../../../button";
import { Popover, PopoverAnchor, PopoverContent } from "../../../popover";
import { useSymbolContext } from "../../../provider/symbolProvider";
import { cn } from "../../../utils/css";
import { commify } from "@orderly.network/utils";
import { Check, X } from "lucide-react";
import { useContext, useEffect, useMemo, useRef, useState } from "react";
import { OrderListContext } from "../shared/orderListContext";
import { toast } from "../../../toast";
import { useSymbolPriceRange } from "@orderly.network/hooks";
import { Tooltip, TooltipArrow, TooltipContent, TooltipTrigger } from "@radix-ui/react-tooltip";
import { Divider } from "../../../divider";
import { cleanStringStyle } from "@orderly.network/hooks";
import { Input } from "../../../input";
export const Price = (props)=>{
    const { order } = props;
    const [price, setPrice] = useState(order.price?.toString() ?? "Market");
    const [open, setOpen] = useState(0);
    const [editting, setEditting] = useState(false);
    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__*/ _jsx("span", {
            children: "Market"
        });
    }
    if (!editting && open <= 0) {
        return /*#__PURE__*/ _jsx(NormalState, {
            order: order,
            price: price,
            setEditing: setEditting
        });
    }
    return /*#__PURE__*/ _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__*/ _jsx("div", {
        className: 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__*/ _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] = useState(false);
    const { editOrder, editAlgoOrder, checkMinNotional } = useContext(OrderListContext);
    const boxRef = useRef(null);
    const confirmRef = useRef(null);
    const { base, base_dp } = useSymbolContext();
    const closePopover = ()=>setOpen(0);
    const cancelPopover = ()=>{
        setOpen(-1);
        setPrice(order.price?.toString() ?? "Market");
    };
    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.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.error(err.message);
            // @ts-ignore
            setPrice(order.price?.toString());
            cancelPopover();
        }).finally(()=>setIsSubmitting(false));
    };
    const inputRef = useRef(null);
    // @ts-ignore
    const rangeInfo = useSymbolPriceRange(order.symbol, // @ts-ignore
    order.side, isAlgoOrder ? order.trigger_price : undefined);
    const hintInfo = 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__*/ _jsx(Popover, {
        open: open > 0,
        onOpenChange: (open)=>setOpen(open ? 1 : 0),
        children: /*#__PURE__*/ _jsxs("div", {
            className: "orderly-flex orderly-justify-start orderly-items-center orderly-gap-1 orderly-relative orderly-font-semibold",
            ref: boxRef,
            children: [
                /*#__PURE__*/ _jsxs("div", {
                    className: 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__*/ _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__*/ _jsx(X, {
                                size: 14
                            })
                        }),
                        /*#__PURE__*/ _jsx(Divider, {
                            vertical: true,
                            className: "orderly-ml-[1px] before:orderly-h-[16px] orderly-min-w-[2px]"
                        })
                    ]
                }),
                /*#__PURE__*/ _jsxs(PopoverAnchor, {
                    children: [
                        isStopMarket && /*#__PURE__*/ _jsx("span", {
                            children: "Market"
                        }),
                        !isStopMarket && /*#__PURE__*/ _jsxs(Tooltip, {
                            open: hintInfo.length > 0,
                            children: [
                                /*#__PURE__*/ _jsx(TooltipTrigger, {
                                    asChild: true,
                                    children: /*#__PURE__*/ _jsx(Input, {
                                        ref: inputRef,
                                        type: "text",
                                        value: commify(price),
                                        onChange: (e)=>setPrice(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__*/ _jsxs(TooltipContent, {
                                    className: "orderly-max-w-[270px] orderly-rounded-lg orderly-bg-base-400 orderly-p-3 orderly-z-50",
                                    align: "center",
                                    children: [
                                        hintInfo,
                                        /*#__PURE__*/ _jsx(TooltipArrow, {
                                            width: 10,
                                            height: 7,
                                            className: "orderly-fill-base-400"
                                        })
                                    ]
                                })
                            ]
                        })
                    ]
                }),
                /*#__PURE__*/ _jsxs("div", {
                    className: 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__*/ _jsx(Divider, {
                            vertical: true,
                            className: "before:orderly-h-[16px] orderly-min-w-[2px] orderly-mr-[1px]"
                        }),
                        /*#__PURE__*/ _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__*/ _jsx(Check, {
                                size: 14
                            })
                        }),
                        /*#__PURE__*/ _jsx(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__*/ _jsxs("div", {
                                className: "orderly-pt-5 orderly-relative",
                                children: [
                                    /*#__PURE__*/ _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__*/ _jsx("span", {
                                                className: "orderly-text-warning",
                                                children: commify(price)
                                            }),
                                            "."
                                        ]
                                    }),
                                    /*#__PURE__*/ _jsxs("div", {
                                        className: "orderly-grid orderly-grid-cols-2 orderly-gap-2 orderly-mt-5",
                                        children: [
                                            /*#__PURE__*/ _jsx(Button, {
                                                color: "tertiary",
                                                onClick: cancelPopover,
                                                disabled: isSubmitting,
                                                children: "Cancel"
                                            }),
                                            /*#__PURE__*/ _jsx(Button, {
                                                ref: confirmRef,
                                                loading: isSubmitting,
                                                onClick: onConfirm,
                                                children: "Confirm"
                                            })
                                        ]
                                    }),
                                    /*#__PURE__*/ _jsx("button", {
                                        className: "orderly-absolute orderly-right-0 orderly-top-0 orderly-text-base-contrast-54",
                                        onClick: cancelPopover,
                                        children: /*#__PURE__*/ _jsx(X, {
                                            size: 18
                                        })
                                    })
                                ]
                            })
                        })
                    ]
                })
            ]
        })
    });
};

//# sourceMappingURL=price.js.map