import { PluginKey, Plugin } from '../../../../../../../node_modules/.pnpm/prosemirror-state@1.4.4/node_modules/prosemirror-state/dist/index.mjs';
import { filterFiles } from '../../utils.mjs';
import { Extension } from '../../../../../../../node_modules/.pnpm/@tiptap_core@3.15.3_@tiptap_pm@3.15.3/node_modules/@tiptap/core/dist/index.mjs';

const FileHandlePlugin = (options) => {
  const {
    key,
    editor,
    onPaste,
    onDrop,
    onValidationError,
    allowedMimeTypes,
    maxFileSize
  } = options;
  return new Plugin({
    key: key || new PluginKey("fileHandler"),
    props: {
      handleDrop(view, event) {
        const { dataTransfer } = event;
        if (!dataTransfer?.files.length) {
          return false;
        }
        event.preventDefault();
        event.stopPropagation();
        const pos = view.posAtCoords({
          left: event.clientX,
          top: event.clientY
        });
        const [validFiles, errors] = filterFiles(
          Array.from(dataTransfer.files),
          {
            allowedMimeTypes,
            maxFileSize,
            allowBase64: options.allowBase64
          }
        );
        if (errors.length > 0 && onValidationError) {
          onValidationError(errors);
        }
        if (validFiles.length > 0 && onDrop) {
          onDrop(editor, validFiles, pos?.pos ?? 0);
        }
        return true;
      },
      handlePaste(_, event) {
        const { clipboardData } = event;
        if (!clipboardData?.files.length) {
          return false;
        }
        event.preventDefault();
        event.stopPropagation();
        const [validFiles, errors] = filterFiles(
          Array.from(clipboardData.files),
          {
            allowedMimeTypes,
            maxFileSize,
            allowBase64: options.allowBase64
          }
        );
        const html = clipboardData.getData("text/html");
        if (errors.length > 0 && onValidationError) {
          onValidationError(errors);
        }
        if (validFiles.length > 0 && onPaste) {
          onPaste(editor, validFiles, html);
        }
        return true;
      }
    }
  });
};
const FileHandler = Extension.create({
  name: "fileHandler",
  addOptions() {
    return {
      allowBase64: false,
      allowedMimeTypes: [],
      maxFileSize: 0
    };
  },
  addProseMirrorPlugins() {
    return [
      FileHandlePlugin({
        key: new PluginKey(this.name),
        editor: this.editor,
        ...this.options
      })
    ];
  }
});

export { FileHandler };
