/* eslint-disable */
import { assertExists } from '@blockeditor/global/utils';
import { INLINE_ROOT_ATTR, type InlineRootElement } from '@blockeditor/inline';
import type { BlockElement, EditorHost } from '@blockeditor/lit';
import type { TemplateResult } from 'lit';
import type { InlineRange } from '@blockeditor/inline';
import type { Flavour } from '../../../models.js';

import { AIIcon } from '../../icons/index.js';
import type {
  AffineTextAttributes,
  AffineInlineEditor,
} from '../../inline/presets/affine-inline-specs.js';
import { toggleAIPopup } from '../../inline/presets/nodes/ai-node/ai-popup/toggle-ai-popup.js';
import { commonActiveWhen } from '../text-format/utils.js';
import { FORMAT_NATIVE_SUPPORT_FLAVOURS } from '../text-format/consts.js';
import { BLOCK_ID_ATTR } from '../../consts.js';

export interface AIPolishConfig {
  id: string;
  name: string;
  icon: TemplateResult<1>;
  hotkey?: string;
  activeWhen: (host: EditorHost) => boolean;
  action: (host: EditorHost) => void;
}

export const aiPolishConfigs: AIPolishConfig[] = [
  {
    id: 'ai',
    name: 'Ask AI',
    icon: AIIcon,
    hotkey: 'Mod-a',
    activeWhen: host => commonActiveWhen(host, 'ai'),
    action: host => {
      let result: AffineInlineEditor[] = [];
      host.std.command
        .pipe()
        .withHost()
        .try(chain => [
          chain
            .getTextSelection()
            .getSelectedBlocks()
            .inline((ctx, next) => {
              const { currentTextSelection, selectedBlocks } = ctx;
              assertExists(currentTextSelection);
              assertExists(selectedBlocks);

              if (currentTextSelection.isCollapsed()) return;

              const selectedInlineEditors = selectedBlocks.flatMap(el => {
                const inlineRoot = el.querySelector<
                  InlineRootElement<AffineTextAttributes>
                >(`[${INLINE_ROOT_ATTR}]`);
                if (inlineRoot && inlineRoot.inlineEditor.getInlineRange()) {
                  return inlineRoot.inlineEditor;
                }
                return [];
              });

              result = selectedInlineEditors
                .filter(inlineEditor => {
                  if (!inlineEditor) return false;
                  const targetInlineRange = inlineEditor.getInlineRange();
                  assertExists(targetInlineRange);
                  if (targetInlineRange.length === 0) return false;

                  return inlineEditor;
                })
                .map(inlineEditor => inlineEditor);
              next();
            }),
          chain.inline(() => {
            const selectedInlineEditors = Array.from<InlineRootElement>(
              host.querySelectorAll(`[${INLINE_ROOT_ATTR}]`)
            )
              .filter(el => {
                const selection = document.getSelection();
                if (!selection || selection.rangeCount === 0) return false;
                const range = selection.getRangeAt(0);

                return range.intersectsNode(el);
              })
              .filter(el => {
                const blockElement = el.closest<BlockElement>(
                  `[${BLOCK_ID_ATTR}]`
                );
                if (blockElement) {
                  return FORMAT_NATIVE_SUPPORT_FLAVOURS.includes(
                    blockElement.model.flavour as Flavour
                  );
                }
                return false;
              })
              .filter(el => {
                const inlineEditor = el.inlineEditor;
                const targetInlineRange = inlineEditor.getInlineRange();
                assertExists(targetInlineRange);
                if (targetInlineRange.length === 0) return false;

                return el;
              })
              .map(el => el.inlineEditor);

            result = selectedInlineEditors;
          }),
        ])
        .run();
      let targetInlineRanges: InlineRange[] = [];
      result.forEach(inlineEditor => {
        const targetInlineRange = inlineEditor.getInlineRange();
        assertExists(targetInlineRange);
        targetInlineRanges.push(targetInlineRange);
      });
      toggleAIPopup(result, 'create', targetInlineRanges);
      // const selection = document.getSelection();
      // if (!selection || selection.rangeCount === 0) return;
      // const range = selection.getRangeAt(0);

      // const inlineRoot = range.commonAncestorContainer.parentElement?.closest<
      // 	InlineRootElement<AffineTextAttributes>
      // >(`[${INLINE_ROOT_ATTR}]`);
      // if (!inlineRoot) return;

      // const inlineEditor = inlineRoot.inlineEditor;
      // const targetInlineRange = inlineEditor.getInlineRange();
      // assertExists(targetInlineRange);

      // if (targetInlineRange.length === 0) return;

      // const format = inlineEditor.getFormat(targetInlineRange);
      // if (format.ai) {
      // 	inlineEditor.formatText(targetInlineRange, { ai: null });
      // 	return;
      // }

      // toggleAIPopup(inlineEditor, 'create', targetInlineRange);
    },
  },
];
