import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
import Button from "../../../button";
import { Divider } from "../../../divider";
import { Input } from "../../../input";
import { Slider } from "../../../slider";
import { Statistic } from "../../../statistic";
import { Text } from "../../../text";
import { useEffect, useMemo } from "react";
import { LimitConfirm } from "./limitConfirm";
import { modal } from "../../../modal";
import { useSymbolsInfo, useOrderEntry } from "@orderly.network/hooks";
import { Controller, useForm } from "react-hook-form";
import { OrderSide, OrderType } from "@orderly.network/types";
import { toast } from "../../../toast";
export const ClosePositionPane = (props)=>{
    const { position, side } = props;
    // const { hide, reject, resolve } = useModal();
    const { markPrice, maxQty, helper, onSubmit } = useOrderEntry(position?.symbol, side, true);
    const { register, handleSubmit, control, getValues, setValue, formState: { errors, submitCount, isSubmitting } } = useForm({
        values: {
            order_price: Math.abs(position?.mark_price),
            order_quantity: Math.abs(position?.position_qty),
            symbol: position?.symbol,
            order_type: OrderType.LIMIT,
            side: side
        },
        resolver: async (values)=>{
            const errors = await helper.validator(values);
            return {
                values,
                errors
            };
        }
    });
    useEffect(()=>{
        // init order_price value
        if (getValues()?.order_price === undefined) {
            //@ts-ignore
            setValue("order_price", markPrice);
        }
    }, [
        markPrice
    ]);
    const symbolInfo = useSymbolsInfo()[position?.symbol];
    //
    const base = useMemo(()=>symbolInfo("base"), [
        symbolInfo
    ]);
    const quote = useMemo(()=>symbolInfo("quote"), [
        symbolInfo
    ]);
    const quoteDp = useMemo(()=>symbolInfo("quote_dp"), [
        symbolInfo
    ]);
    const typeText = useMemo(()=>{
        if (side === OrderSide.SELL) return /*#__PURE__*/ _jsx(Text, {
            type: "sell",
            children: "Limit Sell"
        });
        return /*#__PURE__*/ _jsx(Text, {
            type: "buy",
            children: "Limit Buy"
        });
    }, [
        side
    ]);
    const onConfirm = (data)=>{
        return modal.confirm({
            title: "Limit Close",
            onCancel: ()=>{
                return Promise.reject();
            },
            content: /*#__PURE__*/ _jsx(LimitConfirm, {
                order: data,
                base: base,
                quote: quote,
                side: side
            })
        });
    };
    const onFormSubmit = (data)=>{
        return onConfirm(data).then(()=>{
            return onSubmit({
                ...data,
                reduce_only: true
            }).then((res)=>{
                //
                if (res.success) {
                // toast.success("successfully");
                }
                props.onClose(res);
            }, (error)=>{
                toast.error(error.message);
            });
        }, ()=>{});
    };
    const onFieldChange = (name, value)=>{
        const newValues = helper.calculate(getValues(), name, value);
        if (name === "order_price") {
            // @ts-ignore
            setValue("order_price", newValues.order_price, {
                shouldValidate: submitCount > 0
            });
        }
        // @ts-ignore
        setValue("order_quantity", newValues.order_quantity, {
            shouldValidate: submitCount > 0
        });
    };
    if (!position) return null;
    return /*#__PURE__*/ _jsxs(_Fragment, {
        children: [
            /*#__PURE__*/ _jsx("div", {
                className: "orderly-pb-3 orderly-pt-5 orderly-text-xs",
                children: /*#__PURE__*/ _jsx(Text, {
                    rule: "symbol",
                    children: position.symbol
                })
            }),
            /*#__PURE__*/ _jsxs("div", {
                className: "orderly-grid orderly-grid-cols-2",
                children: [
                    /*#__PURE__*/ _jsx(Statistic, {
                        label: "Order type",
                        value: typeText,
                        valueClassName: "orderly-text-2xs",
                        labelClassName: "orderly-text-4xs orderly-text-base-contrast-36"
                    }),
                    /*#__PURE__*/ _jsx(Statistic, {
                        label: "Last price",
                        value: markPrice,
                        precision: quoteDp,
                        rule: "price",
                        labelClassName: "orderly-text-4xs orderly-text-base-contrast-36",
                        valueClassName: "orderly-text-2xs"
                    })
                ]
            }),
            /*#__PURE__*/ _jsx(Divider, {
                className: "orderly-py-5"
            }),
            /*#__PURE__*/ _jsxs("form", {
                onSubmit: handleSubmit(onFormSubmit),
                children: [
                    /*#__PURE__*/ _jsxs("div", {
                        className: "orderly-flex orderly-flex-col orderly-gap-5",
                        children: [
                            /*#__PURE__*/ _jsx(Controller, {
                                name: "order_price",
                                control: control,
                                render: ({ field })=>{
                                    return /*#__PURE__*/ _jsx(Input, {
                                        prefix: "Price",
                                        suffix: quote,
                                        type: "text",
                                        inputMode: "decimal",
                                        helpText: errors.order_price?.message,
                                        error: !!errors.order_price,
                                        className: "orderly-text-right orderly-text-3xs",
                                        containerClassName: "orderly-bg-base-500 orderly-rounded-borderRadius",
                                        value: field.value,
                                        onChange: (e)=>{
                                            // field.onChange(e.target.value)
                                            onFieldChange("order_price", e.target.value);
                                        }
                                    });
                                }
                            }),
                            /*#__PURE__*/ _jsx(Controller, {
                                name: "order_quantity",
                                control: control,
                                render: ({ field })=>{
                                    return /*#__PURE__*/ _jsx(Input, {
                                        prefix: "Quantity",
                                        suffix: base,
                                        type: "text",
                                        inputMode: "decimal",
                                        containerClassName: "orderly-bg-base-500 orderly-rounded-borderRadius",
                                        helpText: errors.order_quantity?.message,
                                        error: !!errors.order_quantity,
                                        className: "orderly-text-right orderly-text-3xs",
                                        value: field.value,
                                        onChange: (e)=>{
                                            // field.onChange(e.target.value)
                                            onFieldChange("order_quantity", e.target.value);
                                        }
                                    });
                                }
                            })
                        ]
                    }),
                    /*#__PURE__*/ _jsx("div", {
                        className: "orderly-py-5",
                        children: /*#__PURE__*/ _jsx(Controller, {
                            name: "order_quantity",
                            control: control,
                            render: ({ field })=>{
                                //
                                return /*#__PURE__*/ _jsx(Slider, {
                                    step: symbolInfo("base_tick"),
                                    min: 0,
                                    max: Math.abs(position.position_qty),
                                    color: "buy",
                                    markCount: 4,
                                    value: [
                                        Number(field.value ?? 0)
                                    ],
                                    onValueChange: (value)=>{
                                        // if (typeof value[0] !== "undefined") {
                                        //   field.onChange(value[0]);
                                        // }
                                        setValue("order_quantity", value[0]);
                                    }
                                });
                            }
                        })
                    }),
                    /*#__PURE__*/ _jsxs("div", {
                        className: "orderly-grid orderly-grid-cols-2 orderly-text-xs orderly-gap-3 orderly-py-5",
                        children: [
                            /*#__PURE__*/ _jsx(Button, {
                                variant: "contained",
                                color: "tertiary",
                                fullWidth: true,
                                type: "button",
                                onClick: ()=>{
                                    props.onCancel?.();
                                },
                                children: "Cancel"
                            }),
                            /*#__PURE__*/ _jsx(Button, {
                                fullWidth: true,
                                type: "submit",
                                loading: isSubmitting,
                                children: "Confirm"
                            })
                        ]
                    })
                ]
            })
        ]
    });
};

//# sourceMappingURL=closeForm.js.map