import AriaAutocomplete from "../aria-autocomplete.min.js";

const TEL_TYPE = "Telephone";
const URL_TYPE = "URL";
const MAILTO_TYPE = "E-Mail";
const INTERNAL_TYPE = "Internal";

export default function(editor) {
  editor.ui.registry.addToggleButton("tdlink", {
    icon: "link",
    tooltip: "Insert/edit link",
    onAction: (_) => {
      const selectedNode = editor.selection.getNode();
      const selectedHtml = editor.selection.getContent();
      const nodeAttributes = editor.dom.getAttribs(selectedNode);
      const target = nodeAttributes.getNamedItem("target");
      const title = nodeAttributes.getNamedItem("title");
      const url = nodeAttributes.getNamedItem("href");
      var initialData = {
        target: (target && target.value === "_blank") || false,
        ...(title && title.value && { title: title.value }),
        ...(selectedHtml && { text: selectedHtml }),
        ...(url && url.value && { url: { value: url.value } }),
      };

      const linkConfig = {
        title: "Insert/edit link",
        body: {
          classes: ["tox-dialog__body", "td-link"],
          type: "panel",
          items: [
            {
              type: "bar",
              items: [
                {
                  type: "urlinput",
                  name: "url",
                  maximized: true,
                },
              ],
            },
            {
              classes: ["test"],
              type: "bar",
              items: [
                {
                  type: "input",
                  name: "title",
                  label: "Title",
                  maximized: true,
                },
                {
                  type: "checkbox",
                  label: "New window",
                  name: "target",
                },
              ],
            },
          ],
        },
        initialData: initialData,
        buttons: [
          {
            enabled: true,
            type: "cancel",
            name: "cancel",
            text: "Cancel",
          },
          {
            enabled: true,
            buttonType: "primary",
            type: "submit",
            name: "submitButton",
            text: "Save",
          },
        ],
        onSubmit: (dialogApi) => {
          const data = dialogApi.getData();
          const selectedNode = editor.selection.getNode();
          const nodeAttributes = {
            href: data.url.value,
            target: data.target ? "_blank" : "_self",
            title: data.title,
          };

          if (selectedNode.nodeName.toLowerCase() === "a") {
            // Update existing link
            editor.dom.setAttribs(selectedNode, nodeAttributes);
          } else if (nodeAttributes.href) {
            // Create a new link with the selected content
            const selectedContent = editor.selection.getContent();
            const newContent = `<a href="${nodeAttributes.href}" target="${nodeAttributes.target}" title="${nodeAttributes.title}">${selectedContent}</a>`;
            editor.selection.setContent(newContent);
          }

          dialogApi.close();
        },
      };
      editor.windowManager.open(linkConfig);

      const autoCompleteInput = document.querySelectorAll(
        "input.tox-textfield[type='url']"
      );

      const getLinkType = (term) => {
        let type = URL_TYPE;
        var protocol = "";
        try {
          var url = new URL(encodeURI(term));
          protocol = url.protocol;
        } catch (error) { }

        if (protocol.includes("mailto")) {
          type = MAILTO_TYPE;
        }

        if (protocol.includes("tel")) {
          type = TEL_TYPE;
        }

        if (term !== null && term !== void 0 && term.startsWith("#")) {
          type = INTERNAL_TYPE;
        }

        return type;
      };

      autoCompleteInput.forEach((input) => {
        const urlWrapper = input.closest(".tox-form__group");
        urlWrapper.classList.add("tox-form-group--maximize");

        AriaAutocomplete(input, {
          inputClassName: "tox-textfield",
          placeholder: "Search or type url",
          source: async (query, render, isFirstCall) => {
            input.value = query;
            if (
              !isFirstCall &&
              query !== window.lodash.get(initialData, "url.value") &&
              !window.lodash.startsWith(query, "#")
            ) {
              const postTypes = ["post", "media", "term"];
              const fetchData = async (postType) => {
                const seachRoot = postType === "media" ? "media" : "search";
                var url = `${window.wpApiSettings.root}${window.wpApiSettings.versionString}${seachRoot}?search=${query}&per_page=20&_locale=user`;
                if (postType !== "media") {
                  url += `&type=${postType}`;
                }
                return fetch(url)
                  .then((response) => response.json())
                  .catch((error) =>
                    console.error(`Error fetching data from ${url}:`, error)
                  );
              };

              return Promise.all(postTypes.map(fetchData))
                .then((data) => {
                  const results = window.lodash.map(data.flat(), (item) => {
                    if (item.type === "attachment") {
                      return {
                        label: window.lodash.get(item, "title.rendered"),
                        value: item.source_url,
                        type: item.type,
                      };
                    }
                    return {
                      label: item.title,
                      value: item.url,
                      type: item.subtype,
                    };
                  });

                  return results;
                })
                .catch((error) => {
                  console.error("Error fetching data:", error);
                });
            } else {
              if (window.lodash.startsWith(query, "#") && !isFirstCall) {
                return false;
              }
              return {
                label: window.lodash.get(initialData, "url.value"),
                value: window.lodash.get(initialData, "url.value"),
              };
            }
          },
          onConfirm: (selection) => {
            window.lodash.set(initialData, "url.value", selection.value);
          },
          onItemRender: (itemData) => {
            return `<span><span class="aria-autocomplete__option--title">${itemData.label}</span><span class="aria-autocomplete__option--info">${itemData.value}</span></span><span class="aria-autocomplete__option--type">${itemData.type}</span>`;
          },
        });
      });
    },
  });
} 