/**
 * 组织架构树组件
 * - 展示组织 -> 项目 -> 柜子层级
 * - 支持右键菜单（添加/编辑/删除）
 */
import { useCallback } from 'react';
import {
  Layout,
  Tree,
  Typography,
  Button,
  Spin,
} from '@arco-design/web-react';
import {
  IconFolder,
  IconDesktop,
  IconRefresh,
} from '@arco-design/web-react/icon';
import {
  type TreeNode,
  type Cabinet,
} from '@/api/devices';

const Sider = Layout.Sider;

/** 树节点类型 */
export type NodeType = 'organization' | 'project' | 'cabinet' | 'all';

/** 内部树节点 */
export interface TreeInternalNode {
  key: string;
  title: string;
  isLeaf: boolean;
  children?: TreeInternalNode[];
  _type: NodeType;
  _id: number;
}

/** 构建 Arco Tree 数据 */
export function buildTreeData(nodes: TreeNode[], parentKey?: string): TreeInternalNode[] {
  const result: TreeInternalNode[] = [];
  for (const n of nodes) {
    const key = parentKey ? `${parentKey}-${n.id}` : `${n.id}`;
    const children = n.children ? buildTreeData(n.children, key) : undefined;
    const nodeType: NodeType = n.children !== undefined
      ? (parentKey ? 'project' : 'organization')
      : 'cabinet';
    result.push({
      key,
      title: n.abstract_id ? `${n.abstract_id} ${n.name || ''}` : n.name,
      isLeaf: !children || children.length === 0,
      children,
      _type: nodeType,
      _id: n.id,
    });
  }
  return result;
}

/** 从树中收集所有柜子 */
export function collectCabinets(nodes: TreeNode[]): Cabinet[] {
  const result: Cabinet[] = [];
  for (const n of nodes) {
    if (n.children) {
      result.push(...collectCabinets(n.children));
    } else if (n.abstract_id) {
      result.push({
        id: n.id,
        abstract_id: n.abstract_id || '',
        imei: n.imei || '',
        name: n.name,
        status: n.status || 0,
      });
    }
  }
  return result;
}

/** 在原始树中按 ID 查找组织节点 */
export function findOrgInTree(nodes: TreeNode[], id: number): TreeNode | undefined {
  for (const n of nodes) {
    if (n.id === id) return n;
    if (n.children) {
      const found = findOrgInTree(n.children, id);
      if (found) return found;
    }
  }
  return undefined;
}

interface OrganizationTreeProps {
  treeData: TreeInternalNode[];
  loading: boolean;
  selectedKeys: string[];
  onSelect: (keys: string[]) => void;
  onReload: () => void;
  onRightClick: (ev: React.MouseEvent, type: NodeType, id: number) => void;
}

export default function OrganizationTree({
  treeData,
  loading,
  selectedKeys,
  onSelect,
  onReload,
  onRightClick,
}: OrganizationTreeProps) {

  /** 渲染树节点标题（带右键菜单） */
  const renderNodeTitle = useCallback(
    (nodeType: NodeType, nodeId: number, title: string, icon: React.ReactNode) => (
      <span
        style={{ display: 'flex', alignItems: 'center', gap: 4 }}
        onContextMenu={(e) => onRightClick(e, nodeType, nodeId)}
      >
        {icon}
        <span style={{ fontSize: 13 }}>{title}</span>
      </span>
    ),
    [onRightClick],
  );

  /** 递归为树节点注入 titleRender */
  const injectTitleRender = useCallback(
    (nodes: TreeInternalNode[]): unknown[] =>
      nodes.map((n) => {
        const icon = n._type === 'cabinet'
          ? <IconDesktop />
          : <IconFolder />;
        return {
          ...n,
          title: renderNodeTitle(n._type, n._id, n.title, icon),
          children: n.children ? injectTitleRender(n.children) : undefined,
        };
      }),
    [renderNodeTitle],
  );

  const renderedTreeData = [
    {
      key: 'all',
      title: renderNodeTitle('all', 0, '全部', <IconFolder />),
      children: injectTitleRender(treeData) as TreeInternalNode[],
    },
  ];

  return (
    <Sider
      width={300}
      style={{
        background: 'var(--color-bg-2)',
        borderRight: '1px solid var(--color-border)',
        overflow: 'auto',
        padding: 12,
      }}
    >
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 12 }}>
        <Typography.Text style={{ fontWeight: 600, fontSize: 14 }}>组织架构</Typography.Text>
        <Button size="small" type="text" icon={<IconRefresh />} onClick={onReload} />
      </div>
      <Spin loading={loading && treeData.length === 0} dot>
        {treeData.length > 0 ? (
          <Tree
            treeData={renderedTreeData as never}
            selectedKeys={selectedKeys}
            onSelect={onSelect as never}
            autoExpandParent
            defaultExpandedKeys={['all']}
            style={{ fontSize: 13 }}
          />
        ) : (
          !loading && <Typography.Text type="secondary">暂无数据</Typography.Text>
        )}
      </Spin>
    </Sider>
  );
}
