import { NodeSelection } from '@tiptap/pm/state';
import type { BlockDefinition } from '../../types';

const linkButton: BlockDefinition = {
  label: 'リンクボタン',
  icon: 'link',
  description: 'リンクボタン',
  isTextMenu: false,
  aliases: ['link', 'button'],
  createActions: (cmd, ctx) => ({
    action: (editor) => {
      ctx.recordUsage(cmd);
      const { $from } = editor.state.selection;
      const pos = $from.before($from.depth);
      editor.chain().focus().setLinkButtonBlock().setBlockAttrs(pos, { class: cmd.class }).run();
    },
    convert: (editor) => {
      const { state } = editor;
      const { selection } = state;
      if (
        editor.isActive('linkButton') ||
        (selection instanceof NodeSelection && selection.node.type.name === 'linkButton')
      ) {
        editor.chain().focus().updateAttributes('linkButton', { class: cmd.class }).run();
      }
    },
    isDisabled: (editor) => {
      const isSame = cmd.class
        ? editor.isActive('linkButton', { class: cmd.class })
        : editor.isActive('linkButton', { class: null }) || editor.isActive('linkButton', { class: '' });
      // 同じ要素 + class なら disable
      if (isSame) {
        return true;
      }
      // 同じ要素だが class が違う場合 → enable
      if (editor.isActive('linkButton')) {
        return false;
      }
      return true;
    },
    isActive: (editor) => editor.isActive('linkButton'),
  }),
};

export default linkButton;
