import { Extension } from "@tiptap/core";
import { PluginKey } from "@tiptap/pm/state";
import Suggestion from "@tiptap/suggestion";
import { createSuggestionRenderer } from "./suggestionRenderer";
import { apiGet } from "@/api/client";
import type { SuggestionItem } from "@/components/SuggestionDropdown.vue";

interface NoteListResponse {
  notes: Array<{ id: number; title: string }>;
}

const wikilinkSuggestionPluginKey = new PluginKey("wikilinkSuggestion");

export const WikilinkSuggestion = Extension.create({
  name: "wikilinkSuggestion",

  addProseMirrorPlugins() {
    return [
      Suggestion<SuggestionItem>({
        editor: this.editor,
        pluginKey: wikilinkSuggestionPluginKey,
        char: "[[",
        allowSpaces: true,
        items: async ({ query }): Promise<SuggestionItem[]> => {
          try {
            const data = await apiGet<NoteListResponse>(
              `/api/notes?q=${encodeURIComponent(query)}&limit=8`
            );
            return data.notes.map((n) => ({
              label: n.title || "Untitled",
              value: n.title || "Untitled",
            }));
          } catch {
            return [];
          }
        },
        command: ({ editor, range, props: item }) => {
          editor
            .chain()
            .focus()
            .deleteRange(range)
            .insertContent(`[[${item.value}]]`)
            .run();
        },
        render: createSuggestionRenderer,
      }),
    ];
  },
});
