import { assertExists } from '@blockeditor/global/utils';
import type { BlockElement } from '@blockeditor/lit';
import { CorrectIcon, InsertIcon } from '../../../../../icons/ai.js';
import { BLOCK_ID_ATTR } from '../../../../../consts.js';
import type { AffineInlineEditor } from '../../../affine-inline-specs.js';

interface AIConfig {
  name: string;
  icon: any;
  hotkey: string | null;
  action: ({
    inlineEditors,
    targetInlineRanges,
    content,
  }: any) => void | Promise<void>;
}

export const textDealConfig: AIConfig[] = [
  {
    name: 'Replace selection',
    icon: CorrectIcon,
    hotkey: null,
    action: ({ inlineEditors, targetInlineRanges, content }) => {
      inlineEditors.forEach((inlineEditor: AffineInlineEditor, index: number) => {
        if (index === 0) {
          inlineEditor.insertText(targetInlineRanges[index], content);
        } else {
			const totalTextLength = inlineEditor.yTextLength;
			const inlineTextLength = targetInlineRanges[index].length;
			if (totalTextLength === inlineTextLength) {
				const blockElement = inlineEditor.rootElement.closest<BlockElement>(
				  `[${BLOCK_ID_ATTR}]`
				);
				assertExists(blockElement);
				const page = blockElement.host.page;
				page.deleteBlock(blockElement.model);
			} else {
			  inlineEditor.deleteText(targetInlineRanges[index]);
			}
        }
      });
      // inlineEditor.setInlineRange({
      // 	index: targetInlineRange.index,
      // 	length: content.length
      // });
    },
  },
  {
    name: 'Insert below',
    icon: InsertIcon,
    hotkey: null,
    action: ({ inlineEditors, content }) => {
		let targetFlavour = 'affine:paragraph';
		const lastIndex : number = inlineEditors.length - 1;
		const inlineEditor: AffineInlineEditor = inlineEditors[lastIndex];
		const blockElement = inlineEditor.rootElement.closest<BlockElement>(
		  `[${BLOCK_ID_ATTR}]`
		);
		assertExists(blockElement);
		const page = blockElement.host.page;
		const parent = page.getParent(blockElement.model);
		assertExists(parent);
		const index = parent.children.indexOf(blockElement.model);
		const props = {
		  text: new page.Text(content),
		};
		page.addBlock(targetFlavour, props, parent, index + 1);
    },
  },
];
