import * as React from 'react';
import { StarterKit } from '../../../../../../node_modules/.pnpm/@tiptap_starter-kit@3.15.3/node_modules/@tiptap/starter-kit/dist/index.mjs';
import { useEditor } from '../../../../../../node_modules/.pnpm/@tiptap_react@3.15.3_@floating-ui_dom@1.7.4_@tiptap_core@3.20.0_@tiptap_pm@3.15.3__@tip_b42b5b2d59902d8a01cd4cc3e2d5dc64/node_modules/@tiptap/react/dist/index.mjs';
import { Typography } from '../../../../../../node_modules/.pnpm/@tiptap_extension-typography@3.15.3_@tiptap_core@3.20.0_@tiptap_pm@3.15.3_/node_modules/@tiptap/extension-typography/dist/index.mjs';
import { TextStyle } from '../../../../../../node_modules/.pnpm/@tiptap_extension-text-style@3.15.3_@tiptap_core@3.20.0_@tiptap_pm@3.15.3_/node_modules/@tiptap/extension-text-style/dist/index.mjs';
import { Selection, Placeholder } from '../../../../../../node_modules/.pnpm/@tiptap_extensions@3.15.3_@tiptap_core@3.20.0_@tiptap_pm@3.15.3__@tiptap_pm@3.15.3/node_modules/@tiptap/extensions/dist/index.mjs';
import { Markdown } from '../../../../../../node_modules/.pnpm/@tiptap_markdown@3.15.3_@tiptap_core@3.20.0_@tiptap_pm@3.15.3__@tiptap_pm@3.15.3/node_modules/@tiptap/markdown/dist/index.mjs';
import { TaskList, TaskItem } from '../../../../../../node_modules/.pnpm/@tiptap_extension-list@3.15.3_@tiptap_core@3.20.0_@tiptap_pm@3.15.3__@tiptap_pm@3.15.3/node_modules/@tiptap/extension-list/dist/index.mjs';
import { TableKit } from '../../../../../../node_modules/.pnpm/@tiptap_extension-table@3.15.3_@tiptap_core@3.20.0_@tiptap_pm@3.15.3__@tiptap_pm@3.15.3/node_modules/@tiptap/extension-table/dist/index.mjs';
import { CodeBlockLowlight } from '../extensions/code-block-lowlight/code-block-lowlight.mjs';
import { Color } from '../extensions/color/color.mjs';
import { HorizontalRule } from '../extensions/horizontal-rule/horizontal-rule.mjs';
import { Image } from '../extensions/image/image.mjs';
import { UnsetAllMarks } from '../extensions/unset-all-marks/unset-all-marks.mjs';
import { ResetMarksOnEnter } from '../extensions/reset-marks-on-enter/reset-marks-on-enter.mjs';
import { FileHandler } from '../extensions/file-handler/index.mjs';
import { MarkdownPaste } from '../extensions/markdown-paste/markdown-paste.mjs';
import { cn } from '../../../lib/utils.mjs';
import { getOutput, randomId, fileToBase64 } from '../utils.mjs';
import { useThrottle } from './use-throttle.mjs';
import { toast } from 'sonner';

async function fakeuploader(file) {
  await new Promise((resolve) => setTimeout(resolve, 3e3));
  const src = await fileToBase64(file);
  return src;
}
const createExtensions = ({
  placeholder,
  uploader,
  output = "html"
}) => [
  StarterKit.configure({
    blockquote: { HTMLAttributes: { class: "block-node" } },
    // bold
    bulletList: { HTMLAttributes: { class: "list-node" } },
    code: { HTMLAttributes: { class: "inline", spellcheck: "false" } },
    codeBlock: false,
    // document
    dropcursor: { width: 2, class: "ProseMirror-dropcursor border" },
    // gapcursor
    // hardBreak
    heading: { HTMLAttributes: { class: "heading-node" } },
    // undoRedo
    horizontalRule: false,
    // italic
    // listItem
    // listKeymap
    link: {
      enableClickSelection: true,
      openOnClick: false,
      HTMLAttributes: {
        class: "link"
      }
    },
    orderedList: { HTMLAttributes: { class: "list-node" } },
    paragraph: { HTMLAttributes: { class: "text-node" } }
    // strike
    // text
    // underline
    // trailingNode
  }),
  Image.configure({
    allowedMimeTypes: ["image/*"],
    maxFileSize: 5 * 1024 * 1024,
    allowBase64: true,
    uploadFn: async (file) => {
      return uploader ? await uploader(file) : await fakeuploader(file);
    },
    onToggle(editor, files, pos) {
      editor.commands.insertContentAt(
        pos,
        files.map((image) => {
          const blobUrl = URL.createObjectURL(image);
          const id = randomId();
          return {
            type: "image",
            attrs: {
              id,
              src: blobUrl,
              alt: image.name,
              title: image.name,
              fileName: image.name
            }
          };
        })
      );
    },
    onImageRemoved({ id, src }) {
      console.log("Image removed", { id, src });
    },
    onValidationError(errors) {
      errors.forEach((error) => {
        toast.error("Image validation error", {
          position: "bottom-right",
          description: error.reason
        });
      });
    },
    onActionSuccess({ action }) {
      const mapping = {
        copyImage: "Copy Image",
        copyLink: "Copy Link",
        download: "Download"
      };
      toast.success(mapping[action], {
        position: "bottom-right",
        description: "Image action success"
      });
    },
    onActionError(error, { action }) {
      const mapping = {
        copyImage: "Copy Image",
        copyLink: "Copy Link",
        download: "Download"
      };
      toast.error(`Failed to ${mapping[action]}`, {
        position: "bottom-right",
        description: error.message
      });
    }
  }),
  FileHandler.configure({
    allowBase64: true,
    allowedMimeTypes: ["image/*"],
    maxFileSize: 5 * 1024 * 1024,
    onDrop: (editor, files, pos) => {
      files.forEach(async (file) => {
        const src = await fileToBase64(file);
        editor.commands.insertContentAt(pos, {
          type: "image",
          attrs: { src }
        });
      });
    },
    onPaste: (editor, files) => {
      files.forEach(async (file) => {
        const src = await fileToBase64(file);
        editor.commands.insertContent({
          type: "image",
          attrs: { src }
        });
      });
    },
    onValidationError: (errors) => {
      errors.forEach((error) => {
        toast.error("Image validation error", {
          position: "bottom-right",
          description: error.reason
        });
      });
    }
  }),
  Color,
  TextStyle,
  Selection,
  Typography,
  UnsetAllMarks,
  HorizontalRule,
  ResetMarksOnEnter,
  CodeBlockLowlight,
  Placeholder.configure({ placeholder: () => placeholder }),
  // Add MarkdownPaste extension when output is markdown
  ...output === "markdown" ? [
    // Markdown with GFM support for tables, task lists, etc.
    Markdown.configure({
      markedOptions: {
        gfm: true
      }
    }),
    // Task lists (checkboxes)
    TaskList.configure({
      HTMLAttributes: { class: "task-list-node" }
    }),
    TaskItem.configure({
      nested: true
    }),
    // Tables
    TableKit.configure({
      table: {
        resizable: true,
        HTMLAttributes: { class: "table-node" }
      }
    }),
    MarkdownPaste
  ] : []
];
const useMinimalTiptapEditor = ({
  value,
  output = "html",
  placeholder = "",
  editorClassName,
  throttleDelay = 0,
  onUpdate,
  onBlur,
  uploader,
  ...props
}) => {
  const throttledSetValue = useThrottle(
    (value2) => onUpdate?.(value2),
    throttleDelay
  );
  const handleUpdate = React.useCallback(
    (editor2) => throttledSetValue(getOutput(editor2, output)),
    [output, throttledSetValue]
  );
  const handleCreate = React.useCallback(
    (editor2) => {
      if (value && editor2.isEmpty) {
        editor2.commands.setContent(value, {
          contentType: output === "markdown" ? "markdown" : void 0
        });
      }
    },
    [value, output]
  );
  const handleBlur = React.useCallback(
    (editor2) => onBlur?.(getOutput(editor2, output)),
    [output, onBlur]
  );
  const editor = useEditor({
    immediatelyRender: false,
    extensions: createExtensions({ placeholder, uploader, output }),
    editorProps: {
      attributes: {
        autocomplete: "off",
        autocorrect: "off",
        autocapitalize: "off",
        class: cn("focus:outline-hidden", editorClassName)
      }
    },
    onUpdate: ({ editor: editor2 }) => handleUpdate(editor2),
    onCreate: ({ editor: editor2 }) => handleCreate(editor2),
    onBlur: ({ editor: editor2 }) => handleBlur(editor2),
    ...props
  });
  return editor;
};

export { useMinimalTiptapEditor as default, useMinimalTiptapEditor };
