<template>
  <UPopover
    v-model:open="open"
    :ui="{ content: 'p-0.5' }"
  >
    <UTooltip text="Ссылка">
      <UButton
        :icon="appConfig.ui.icons.link"
        color="neutral"
        active-color="primary"
        variant="ghost"
        active-variant="soft"
        size="sm"
        :active="active"
        :disabled="disabled"
      />
    </UTooltip>

    <template #content>
      <UInput
        v-model="url"
        autofocus
        name="url"
        type="url"
        variant="none"
        placeholder="Выставить ссылку..."
        @keydown="handleKeyDown"
      >
        <div class="flex items-center mr-0.5">
          <UButton
            :icon="appConfig.ui.icons.enter"
            variant="ghost"
            size="sm"
            :disabled="!url && !active"
            title="Выставить ссылку"
            @click="setLink"
          />

          <USeparator
            orientation="vertical"
            class="h-6 mx-1"
          />

          <UButton
            :icon="appConfig.ui.icons.external"
            color="neutral"
            variant="ghost"
            size="sm"
            :disabled="!url && !active"
            title="Открыть в новом окне"
            @click="openLink"
          />

          <UButton
            :icon="appConfig.ui.icons.trash"
            color="neutral"
            variant="ghost"
            size="sm"
            :disabled="!url && !active"
            title="Удалить ссылку"
            @click="removeLink"
          />
        </div>
      </UInput>
    </template>
  </UPopover>
</template>

<script setup>
import { useAppConfig } from "#imports";
import { computed, ref, watch } from "vue";
const props = defineProps({
  editor: { type: Object, required: true },
  autoOpen: { type: Boolean, required: false }
});
const appConfig = useAppConfig();
const open = ref(false);
const url = ref("");
const active = computed(() => props.editor.isActive("link"));
const disabled = computed(() => {
  if (!props.editor.isEditable) {
    return true;
  }
  const { selection } = props.editor.state;
  return selection.empty && !props.editor.isActive("link");
});
watch(() => props.editor, (editor, _, onCleanup) => {
  if (!editor) {
    return;
  }
  const updateUrl = () => {
    const { href } = editor.getAttributes("link");
    url.value = href || "";
  };
  updateUrl();
  editor.on("selectionUpdate", updateUrl);
  onCleanup(() => {
    editor.off("selectionUpdate", updateUrl);
  });
}, { immediate: true });
watch(active, (isActive) => {
  if (isActive && props.autoOpen) {
    open.value = true;
  }
});
function setLink() {
  if (!url.value) {
    return;
  }
  const { selection } = props.editor.state;
  const isEmpty = selection.empty;
  let chain = props.editor.chain().focus();
  chain = chain.extendMarkRange("link").setLink({ href: url.value });
  if (isEmpty) {
    chain = chain.insertContent({ type: "text", text: url.value });
  }
  chain.run();
  open.value = false;
}
function removeLink() {
  props.editor.chain().focus().extendMarkRange("link").unsetLink().setMeta("preventAutolink", true).run();
  url.value = "";
  open.value = false;
}
function openLink() {
  if (!url.value) {
    return;
  }
  window.open(url.value, "_blank", "noopener,noreferrer");
}
function handleKeyDown(event) {
  if (event.key === "Enter") {
    event.preventDefault();
    setLink();
  }
}
</script>
