import { useGetEntityListSubTree, useAccessorTreeState, AccessorTree, Entity } from "@contember/binding";
import { useDialog, Stack, Button } from "@contember/ui";
import { useMemo } from "react";
import { choiceFieldDictionary } from "../choiceFieldDictionary.js";
import { useDesugaredOptionPath } from "./useDesugaredOptionPath.js";
import { jsxs, jsx } from "react/jsx-runtime";
import { useMessageFormatter } from "../../../../../i18n/useMessageFormatter.js";
const useOnAddNew = ({
  createNewForm,
  connect,
  ...props
}) => {
  const desugaredOptionPath = useDesugaredOptionPath(props, void 0);
  const getSubTree = useGetEntityListSubTree();
  const dialog = useDialog();
  const localization = useMessageFormatter(choiceFieldDictionary);
  const accessorTreeState = useAccessorTreeState();
  return useMemo(() => {
    if (!createNewForm) {
      return void 0;
    }
    return async () => {
      const subTree = getSubTree({
        entities: {
          entityName: desugaredOptionPath.entityName
        },
        limit: 0
      });
      const newEntityId = subTree.createNewEntity();
      const entity = subTree.getChildEntityById(newEntityId.value);
      const result = await dialog.openDialog({
        heading: localization("choiceField.createNew.dialogTitle"),
        content: (contentProps) => /* @__PURE__ */ jsxs(Stack, {
          direction: "vertical",
          children: [/* @__PURE__ */ jsx(AccessorTree, {
            state: accessorTreeState,
            children: /* @__PURE__ */ jsx(Entity, {
              accessor: entity,
              children: createNewForm
            })
          }), /* @__PURE__ */ jsxs(Stack, {
            direction: "horizontal",
            evenly: true,
            children: [/* @__PURE__ */ jsx(Button, {
              onClick: () => contentProps.resolve(),
              distinction: "default",
              elevation: "none",
              children: localization("choiceField.createNew.cancelButtonText")
            }), /* @__PURE__ */ jsx(Button, {
              onClick: () => contentProps.resolve(true),
              distinction: "primary",
              elevation: "none",
              children: localization("choiceField.createNew.confirmButtonText")
            })]
          })]
        })
      });
      if (result === true) {
        const entityToConnect = entity.getAccessor();
        connect(entityToConnect);
      } else {
        entity.deleteEntity();
      }
    };
  }, [createNewForm, getSubTree, desugaredOptionPath.entityName, dialog, accessorTreeState, localization, connect]);
};
export {
  useOnAddNew
};
//# sourceMappingURL=useOnAddNew.js.map
