import { memo, useMemo, createElement } from "react";
import { BindingError, Entity } from "@contember/binding";
import { Box, ActionableBox, toEnumViewClass } from "@contember/ui";
import { ErrorFilePreview } from "./ErrorFilePreview.js";
import { InitializedFilePreview } from "./InitializedFilePreview.js";
import { InitializingFilePreview } from "./InitializingFilePreview.js";
import { UploadedFilePreview } from "./UploadedFilePreview.js";
const viewFromMimeTypeRegExp = new RegExp(/^(\w+).*/);
function viewFromMimeType(mimeType) {
  if (!mimeType)
    return;
  return (Array.isArray(mimeType) ? mimeType[0] : mimeType).replace(viewFromMimeTypeRegExp, "$1");
}
const SingleFilePreview = memo(({ fileId, resolvedEntity, formatMessage, removeFile, uploadState }) => {
  let preview = null;
  const onRemove = useMemo(() => {
    if (!removeFile) {
      return void 0;
    }
    return () => {
      removeFile(fileId);
    };
  }, [fileId, removeFile]);
  if (uploadState !== void 0) {
    if (uploadState.readyState === "initializing") {
      return /* @__PURE__ */ createElement(InitializingFilePreview, {
        formatMessage
      });
    }
    if (uploadState.readyState === "error" && resolvedEntity.fileKind === void 0) {
      preview = /* @__PURE__ */ createElement(ErrorFilePreview, {
        uploadState,
        formatMessage
      });
    } else {
      if (resolvedEntity.fileKind === void 0) {
        throw new BindingError();
      }
      preview = /* @__PURE__ */ createElement(InitializedFilePreview, {
        fileKind: resolvedEntity.fileKind,
        formatMessage,
        resolvedEntity,
        uploadState
      });
    }
  } else if (!resolvedEntity.isEmpty) {
    preview = /* @__PURE__ */ createElement(UploadedFilePreview, {
      fileKind: resolvedEntity.fileKind
    });
  } else {
    return null;
  }
  let editContents = resolvedEntity.fileKind && resolvedEntity.fileKind.children ? /* @__PURE__ */ createElement(Box, null, resolvedEntity.fileKind.children) : void 0;
  if (resolvedEntity.fileKind?.childrenOutsideBaseEntity) {
    editContents = /* @__PURE__ */ createElement(Entity, {
      accessor: resolvedEntity.parentEntity
    }, editContents);
  }
  const box = /* @__PURE__ */ createElement(ActionableBox, {
    className: toEnumViewClass(viewFromMimeType(resolvedEntity.fileKind?.acceptMimeTypes)),
    onRemove,
    editContents
  }, preview);
  return resolvedEntity.fileEntity ? /* @__PURE__ */ createElement(Entity, {
    accessor: resolvedEntity.fileEntity
  }, box) : box;
});
SingleFilePreview.displayName = "SingleFilePreview";
export { SingleFilePreview };
//# sourceMappingURL=SingleFilePreview.js.map
