import { jsx as _jsx } from "react/jsx-runtime";
import { OrderType } from "@orderly.network/types";
import { createContext, useContext, useEffect, useMemo, useState } from "react";
import { OrderSide } from "@orderly.network/types";
import { useOrderEntry } from "@orderly.network/hooks";
export const PositionsRowContext = /*#__PURE__*/ createContext({});
export const usePositionsRowContext = ()=>{
    return useContext(PositionsRowContext);
};
export const PositionsRowProvider = (props)=>{
    const [quantity, setQuantity] = useState(Math.abs(props.position.position_qty).toString());
    useEffect(()=>{
        setQuantity(Math.abs(props.position.position_qty).toString());
    }, [
        props.position.position_qty
    ]);
    const [price, setPrice] = useState("");
    const [side, setSide] = useState(props.position.position_qty > 0 ? OrderSide.SELL : OrderSide.BUY);
    const [type, setType] = useState(OrderType.MARKET);
    const { helper, onSubmit, submitting } = useOrderEntry(props.position?.symbol, side, true);
    const updateOrderType = (type, price)=>{
        setType(type);
        if (type === OrderType.LIMIT) {
            if (!price) {
                throw new Error("price is required");
            }
            setPrice(price);
        } else {
            setPrice("");
        }
    };
    const closeOrderData = useMemo(()=>{
        const { position } = props;
        if (!position) return null;
        const data = {
            //   order_price: undefined,
            order_quantity: quantity,
            symbol: props.position.symbol,
            order_type: type,
            side,
            reduce_only: true
        };
        if (type === OrderType.LIMIT) {
            data.order_price = price;
        }
        return data;
    }, [
        props.position,
        price,
        type,
        quantity
    ]);
    const onUpdateQuantity = (value)=>{
        const newValues = helper.calculate({}, "order_quantity", value);
        setQuantity(newValues["order_quantity"]);
    };
    const onUpdatePrice = (value)=>{
        const newValues = helper.calculate({}, "order_price", value);
        setPrice(newValues["order_price"]);
    };
    const postOrder = ()=>{
        return onSubmit(closeOrderData);
    };
    return /*#__PURE__*/ _jsx(PositionsRowContext.Provider, {
        value: {
            quantity,
            price,
            type,
            side,
            position: props.position,
            updatePriceChange: onUpdatePrice,
            updateQuantity: onUpdateQuantity,
            updateOrderType,
            onSubmit: postOrder,
            submitting,
            closeOrderData
        },
        children: props.children
    });
};

//# sourceMappingURL=positionRowContext.js.map