/**
 * Table Node Extension
 * 表格节点
 */

import type { NodeSpec, Schema, SlashMenuItem } from '../../core/types';
import { NodeExtension } from '../../core/Extension';
import { TableIcon } from 'lucide-react';

export interface TableOptions {
  /** 是否允许调整列宽 */
  resizable?: boolean;
}

export class Table extends NodeExtension<TableOptions> {
  get name(): string {
    return 'table';
  }

  get schema(): NodeSpec {
    return {
      content: 'tableRow+',
      tableRole: 'table',
      isolating: true,
      group: 'block',
      parseDOM: [{ tag: 'table' }],
      toDOM() {
        return [
          'div',
          { class: 'editor-table-wrapper' },
          ['table', { class: 'editor-table' }, ['tbody', 0]],
        ];
      },
    };
  }

  slashMenuItems(schema: Schema): SlashMenuItem[] {
    const tableType = schema.nodes.table;
    const tableRowType = schema.nodes.tableRow;
    const tableCellType = schema.nodes.tableCell;

    if (!tableType || !tableRowType || !tableCellType) return [];

    return [
      {
        name: 'table',
        title: '表格',
        description: '插入表格',
        icon: TableIcon,
        keywords: ['table', '表格', 'biaoge'],
        group: 'blocks',
        priority: 30,
        command: (state, dispatch) => {
          // 创建一个 3x3 的表格
          const cells = [];
          for (let i = 0; i < 3; i++) {
            cells.push(
              tableCellType.createAndFill({ header: i === 0 }) ||
                tableCellType.create({ header: i === 0 })
            );
          }

          const rows = [];
          for (let i = 0; i < 3; i++) {
            const rowCells = [];
            for (let j = 0; j < 3; j++) {
              rowCells.push(
                tableCellType.createAndFill({ header: i === 0 }) ||
                  tableCellType.create({ header: i === 0 })
              );
            }
            rows.push(tableRowType.create(null, rowCells));
          }

          const table = tableType.create(null, rows);
          const tr = state.tr.replaceSelectionWith(table);

          if (dispatch) {
            dispatch(tr.scrollIntoView());
          }
          return true;
        },
      },
    ];
  }
}

export default Table;
