import { useMemo, createElement } from "react";
import { useGetEntityListSubTree, useAccessorTreeState, NIL_UUID, AccessorTree, Entity } from "@contember/binding";
import { useDialog, Stack, Button } from "@contember/ui";
import { choiceFieldDictionary } from "../choiceFieldDictionary.js";
import { useDesugaredOptionPath } from "./useDesugaredOptionPath.js";
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,
          filter: { id: { eq: NIL_UUID } }
        }
      });
      const newEntityId = subTree.createNewEntity();
      const entity = subTree.getChildEntityById(newEntityId.value);
      const result = await dialog.openDialog({
        heading: localization("choiceField.createNew.dialogTitle"),
        content: (contentProps) => /* @__PURE__ */ createElement(Stack, {
          direction: "vertical"
        }, /* @__PURE__ */ createElement(AccessorTree, {
          state: accessorTreeState
        }, /* @__PURE__ */ createElement(Entity, {
          accessor: entity
        }, createNewForm)), /* @__PURE__ */ createElement(Stack, {
          direction: "horizontal",
          evenly: true
        }, /* @__PURE__ */ createElement(Button, {
          onClick: () => contentProps.resolve(),
          distinction: "default",
          elevation: "none"
        }, localization("choiceField.createNew.cancelButtonText")), /* @__PURE__ */ createElement(Button, {
          onClick: () => contentProps.resolve(true),
          distinction: "primary",
          elevation: "none"
        }, 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
