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

const table: BlockDefinition = {
  label: 'テーブル',
  icon: 'table',
  description: 'テーブル',
  isTextMenu: false,
  aliases: ['table'],
  createActions: (cmd, ctx) => ({
    action: (editor) => {
      ctx.recordUsage(cmd);
      editor.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: false }).run();
      const { $from } = editor.state.selection;
      // カーソル位置から上へ順に探索して `table` を見つける
      for (let { depth } = $from; depth > 0; depth--) {
        const node = $from.node(depth);
        if (node.type.name === 'table') {
          const pos = $from.before(depth);
          editor.chain().focus().setBlockAttrs(pos, { class: cmd.class }).run();
          break;
        }
      }
    },
    convert: (editor) => {
      const { state } = editor;
      const { selection } = state;
      if (editor.isActive('table') || (selection instanceof NodeSelection && selection.node.type.name === 'table')) {
        editor.chain().focus().updateAttributes('table', { class: cmd.class }).run();
      }
    },
    isDisabled: (editor) => {
      const isSame = cmd.class
        ? editor.isActive('table', { class: cmd.class })
        : editor.isActive('table', { class: null }) || editor.isActive('table', { class: '' });
      // 同じ要素 + class なら disable
      if (isSame) {
        return true;
      }
      // 同じ要素だが class が違う場合 → enable
      if (editor.isActive('table')) {
        return false;
      }
      return true;
    },
    isActive: (editor) => editor.isActive('table'),
  }),
};

export default table;
