/**
 * Heading Node Extension
 * 标题节点 (h1-h6)
 */

import type { NodeSpec, Schema, Command, SlashMenuItem, InputRule } from '../../core/types';
import { NodeExtension } from '../../core/Extension';
import { setBlockType } from 'prosemirror-commands';
import { textblockTypeInputRule } from 'prosemirror-inputrules';
import { Heading1, Heading2, Heading3, Heading4, Heading5, Heading6 } from 'lucide-react';

export interface HeadingOptions {
  levels: number[];
}

export class Heading extends NodeExtension<HeadingOptions> {
  get name(): string {
    return 'heading';
  }

  get defaultOptions(): HeadingOptions {
    return {
      levels: [1, 2, 3, 4, 5, 6],
    };
  }

  get schema(): NodeSpec {
    return {
      attrs: {
        level: { default: 1 },
        id: { default: null },
      },
      content: 'inline*',
      group: 'block',
      defining: true,
      parseDOM: this.options.levels.map((level) => ({
        tag: `h${level}`,
        getAttrs: (dom: HTMLElement) => ({
          level,
          id: dom.getAttribute('id'),
        }),
      })),
      toDOM(node) {
        const level = node.attrs.level as number;
        const id = node.attrs.id as string | null;
        const attrs: Record<string, string> = {
          class: `editor-heading editor-heading-${level}`,
        };
        if (id) {
          attrs.id = id;
        }
        return [`h${level}`, attrs, 0];
      },
    };
  }

  inputRules(schema: Schema): InputRule[] {
    const rules: InputRule[] = [];

    for (const level of this.options.levels) {
      // 匹配 # 到 ###### 开头
      const pattern = new RegExp(`^(#{${level}})\\s$`);
      rules.push(
        textblockTypeInputRule(pattern, schema.nodes.heading, () => ({
          level,
        }))
      );
    }

    return rules;
  }

  keys(schema: Schema): Record<string, Command> {
    const keys: Record<string, Command> = {};

    // Cmd/Ctrl + Alt + 1-6 切换标题级别
    for (const level of this.options.levels) {
      keys[`Mod-Alt-${level}`] = setBlockType(schema.nodes.heading, { level });
    }

    return keys;
  }

  slashMenuItems(schema: Schema): SlashMenuItem[] {
    const icons = {
      1: Heading1,
      2: Heading2,
      3: Heading3,
      4: Heading4,
      5: Heading5,
      6: Heading6,
    };

    const titles = {
      1: '一级标题',
      2: '二级标题',
      3: '三级标题',
      4: '四级标题',
      5: '五级标题',
      6: '六级标题',
    };

    const descriptions = {
      1: '大标题',
      2: '中标题',
      3: '小标题',
      4: '四级标题',
      5: '五级标题',
      6: '六级标题',
    };

    return this.options.levels.slice(0, 4).map((level) => ({
      name: `heading${level}`,
      title: titles[level as keyof typeof titles],
      description: descriptions[level as keyof typeof descriptions],
      icon: icons[level as keyof typeof icons],
      keywords: [`heading${level}`, `h${level}`, '标题', `${level}级`],
      command: setBlockType(schema.nodes.heading, { level }),
      group: 'heading',
      priority: 90 - level,
    }));
  }
}
