import { TreeNodeConfig, TreeNodeCheckState, TreeOptions } from './types';
/**
 * 树节点类
 * 负责渲染单个节点、处理交互和递归
 */
export class BimTreeNode {
    public config: TreeNodeConfig;
    public element: HTMLElement;
    public children: BimTreeNode[] = [];
    public parent: BimTreeNode | null = null;
    public checkState: TreeNodeCheckState = TreeNodeCheckState.Unchecked;

        // UI Elements
        private contentEl!: HTMLElement;
        private switcherEl!: HTMLElement;
        private checkboxEl: HTMLElement | null = null;
        private titleEl!: HTMLElement;
        private actionsEl!: HTMLElement; // 操作栏容器
        private childrenContainer!: HTMLElement;
        // 外部回调
        private onExpandChange: (node: BimTreeNode) => void;
        private onCheckChange: (node: BimTreeNode) => void;
        private onNodeClick: (node: BimTreeNode) => void;
        private renderActions?: (node: TreeNodeConfig) => HTMLElement | string;
    
        constructor(
            config: TreeNodeConfig, 
            options: TreeOptions,
            callbacks: {
                onExpand: (n: BimTreeNode) => void,
                onCheck: (n: BimTreeNode) => void,
                onClick: (n: BimTreeNode) => void
            }
        ) {
            this.config = config;
            this.onExpandChange = callbacks.onExpand;
            this.onCheckChange = callbacks.onCheck;
            this.onNodeClick = callbacks.onClick;
            this.renderActions = options.renderActions;
            
            // 初始化状态
            this.checkState = config.checked ? TreeNodeCheckState.Checked : TreeNodeCheckState.Unchecked;
    
            this.element = this.createDom(options);
        }
    /**
     * 创建节点 DOM
     */
    private createDom(options: TreeOptions): HTMLElement {
        const nodeEl = document.createElement('div');
        nodeEl.className = 'bim-tree-node';
        if (this.config.disabled) nodeEl.classList.add('is-disabled');

        // 1. 内容行
        this.contentEl = document.createElement('div');
        this.contentEl.className = 'bim-tree-node-content';

        // 1.1 展开/折叠箭头
        this.switcherEl = document.createElement('span');
        this.switcherEl.className = 'bim-tree-switcher';
        // 默认右箭头 SVG
        this.switcherEl.innerHTML = `<svg viewBox="0 0 1024 1024"><path d="M288 192l448 320-448 320z"></path></svg>`;

        const hasChildren = this.config.children && this.config.children.length > 0;
        if (!hasChildren) {
            this.switcherEl.classList.add('is-hidden');
        } else if (this.config.expanded) {
            this.switcherEl.classList.add('is-expanded');
        }

        this.switcherEl.addEventListener('click', (e) => {
            e.stopPropagation();
            this.toggleExpand();
        });

        this.contentEl.appendChild(this.switcherEl);

        // 1.2 复选框 (可选)
        if (options.checkable !== false) {
            this.checkboxEl = document.createElement('span');
            this.checkboxEl.className = 'bim-tree-checkbox';
            this.updateCheckboxUI();

            this.checkboxEl.addEventListener('click', (e) => {
                e.stopPropagation();
                if (this.config.disabled) return;
                this.toggleCheck();
            });
            this.contentEl.appendChild(this.checkboxEl);
        }

        // 1.3 图标 (可选)
        if (this.config.icon) {
            const iconEl = document.createElement('span');
            iconEl.className = 'bim-tree-icon';
            iconEl.innerHTML = this.config.icon.includes('<svg')
                ? this.config.icon
                : `<img src="${this.config.icon}" />`;
            this.contentEl.appendChild(iconEl);
        }

        // 1.4 文本
        this.titleEl = document.createElement('span');
        this.titleEl.className = 'bim-tree-title';
        this.updateLabel(); // 设置文本
        this.contentEl.appendChild(this.titleEl);

        // 1.5 操作栏 (Actions)
        this.actionsEl = document.createElement('div');
        this.actionsEl.className = 'bim-tree-node-actions';
        this.actionsEl.addEventListener('click', (e) => {
            e.stopPropagation(); // 防止点击操作栏触发选中/展开
        });
        this.contentEl.appendChild(this.actionsEl);

        // 绑定整行点击
        this.contentEl.addEventListener('click', (e) => {
            e.stopPropagation();
            if (this.config.disabled) return;

            const action = this.config.clickAction || 'select';

            if (action === 'expand') {
                this.toggleExpand();
            } else {
                this.onNodeClick(this);
            }
        });

        nodeEl.appendChild(this.contentEl);

        // 2. 子节点容器
        this.childrenContainer = document.createElement('div');
        this.childrenContainer.className = 'bim-tree-children';
        // 设置缩进
        const indent = options.indent || 24;
        this.childrenContainer.style.paddingLeft = `${indent}px`; // 每一级子器左移

        if (this.config.expanded && hasChildren) {
            this.childrenContainer.classList.add('is-visible');
        }
        nodeEl.appendChild(this.childrenContainer);

        return nodeEl;
    }

    /**
     * 设置高亮选中状态 (Select 模式下)
     */
    public setSelected(selected: boolean) {
        if (selected) {
            this.contentEl.classList.add('is-selected');
            // 渲染自定义操作栏
            if (this.renderActions) {
                const content = this.renderActions(this.config);
                this.actionsEl.innerHTML = '';
                if (typeof content === 'string') {
                    this.actionsEl.innerHTML = content;
                } else if (content instanceof HTMLElement) {
                    this.actionsEl.appendChild(content);
                }
            }
        } else {
            this.contentEl.classList.remove('is-selected');
            this.actionsEl.innerHTML = ''; // 清空内容
        }
    }

    /**
     * 更新显示文本 (国际化支持) -> 移除国际化，直接显示
     */
    public updateLabel() {
        if (this.titleEl) {
            this.titleEl.textContent = this.config.label;
        }
    }

    /**
     * 切换展开状态
     */
    public toggleExpand(force?: boolean) {
        if (!this.config.children || this.config.children.length === 0) return;

        const newState = force !== undefined ? force : !this.config.expanded;
        this.config.expanded = newState;

        if (newState) {
            this.switcherEl.classList.add('is-expanded');
            this.childrenContainer.classList.add('is-visible');
        } else {
            this.switcherEl.classList.remove('is-expanded');
            this.childrenContainer.classList.remove('is-visible');
        }

        // 触发回调
        if (force === undefined) { // 只有用户交互才触发回调，防止初始化时无限循环
             this.onExpandChange(this);
        }
    }

    /**
     * 切换选中状态 (用户点击)
     */
    public toggleCheck() {
        // 如果当前是半选，点击变全选；如果全选，点击未选；如果未选，点击变全选
        // 简化逻辑：只要不是 Checked，点击都变 Checked；如果是 Checked，变 Unchecked
        const newChecked = this.checkState !== TreeNodeCheckState.Checked;
        this.setChecked(newChecked ? TreeNodeCheckState.Checked : TreeNodeCheckState.Unchecked, true);
    }

    /**
     * 设置选中状态 (API调用或联动)
     * @param state 新状态
     * @param fireEvent 是否触发事件
     */
    public setChecked(state: TreeNodeCheckState, fireEvent: boolean = false) {
        if (this.checkState === state) return;

        this.checkState = state;
        this.config.checked = (state === TreeNodeCheckState.Checked);

        this.updateCheckboxUI();

        if (fireEvent) {
            this.onCheckChange(this);
        }
    }

    /**
     * 更新复选框 UI 样式
     */
    public updateCheckboxUI() {
        if (!this.checkboxEl) return;

        this.checkboxEl.classList.remove('is-checked', 'is-indeterminate');

        if (this.checkState === TreeNodeCheckState.Checked) {
            this.checkboxEl.classList.add('is-checked');
        } else if (this.checkState === TreeNodeCheckState.Indeterminate) {
            this.checkboxEl.classList.add('is-indeterminate');
        }
    }

    /**
     * 添加子节点实例
     */
    public appendChild(childNode: BimTreeNode) {
        childNode.parent = this;
        this.children.push(childNode);
        this.childrenContainer.appendChild(childNode.element);

        // 如果之前是隐藏的箭头，现在有了子节点，需要显示出来
        if (this.children.length === 1) {
            this.switcherEl.classList.remove('is-hidden');
        }
    }

    /**
     * 销毁
     */
    public destroy() {
        this.children.forEach(c => c.destroy());
        this.children = [];
        this.element.remove();
        this.parent = null;
    }
}
