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

const file: BlockDefinition = {
  label: 'ファイル',
  icon: 'draft',
  description: 'メディアファイル',
  isTextMenu: false,
  aliases: ['file', 'media'],
  createActions: (cmd, ctx) => ({
    action: (editor) => {
      ctx.recordUsage(cmd);
      const { $from } = editor.state.selection;
      const pos = $from.before($from.depth);
      editor.chain().focus().uploadMediaFile().setBlockAttrs(pos, { class: cmd.class }).run();
    },
    convert: (editor) => {
      const { state } = editor;
      const { selection } = state;
      if (
        editor.isActive('fileBlock') ||
        (selection instanceof NodeSelection && selection.node.type.name === 'fileBlock')
      ) {
        editor.chain().focus().updateAttributes('fileBlock', { class: cmd.class }).run();
      }
    },
    isDisabled: (editor) => {
      const isSame = cmd.class
        ? editor.isActive('fileBlock', { class: cmd.class })
        : editor.isActive('fileBlock', { class: null }) || editor.isActive('fileBlock', { class: '' });
      // 同じ要素 + class なら disable
      if (isSame) {
        return true;
      }
      // 同じ要素だが class が違う場合 → enable
      if (editor.isActive('fileBlock')) {
        return false;
      }
      return true;
    },
    isActive: (editor) => editor.isActive('fileBlock'),
  }),
};

export default file;
