import React, { useEffect, useState } from 'react';
import { Input, Tree } from '@arco-design/web-react';
import { IconSearch } from '@arco-design/web-react/icon';
import { getTreeComponents } from '@/api/componentTestCase';
import styles from './style/sideBar.module.less';

const TreeNode = Tree.Node;

const SideBar = ({ onNodeSelect, getCount }) => {
  const [searchValue, setSearchValue] = useState('');
  const [treeData, setTreeData] = useState([]);
  const [originalData, setOriginalData] = useState([]);
  const [expandedKeys, setExpandedKeys] = useState<string[]>([]);

  const handleSearchChange = (value: string) => {
    setSearchValue(value);

    if (!value.trim()) {
      // 搜索为空时,恢复原始数据并收起所有节点
      setTreeData(originalData);
      setExpandedKeys([]);
      return;
    }

    // 过滤树形数据
    const filterTreeData = (data: any[]) => {
      const filtered: any[] = [];
      const expandKeys: string[] = [];

      data.forEach((classifyNode) => {
        const filteredChildren = classifyNode.children.filter((child: any) =>
          child.title.toLowerCase().includes(value.toLowerCase())
        );

        // 如果有匹配的子节点,或者分类名称匹配
        if (
          filteredChildren.length > 0 ||
          classifyNode.title.toLowerCase().includes(value.toLowerCase())
        ) {
          filtered.push({
            ...classifyNode,
            children: filteredChildren.length > 0 ? filteredChildren : classifyNode.children
          });
          // 展开匹配的分类
          expandKeys.push(classifyNode.key);
        }
      });

      return { filtered, expandKeys };
    };

    const { filtered, expandKeys } = filterTreeData(originalData);
    setTreeData(filtered);
    setExpandedKeys(expandKeys);
  };

  // 根据 componentClassify 分类数据
  const formatTreeData = (data: any[]) => {
    const classifyMap = new Map();

    data.forEach((item) => {
      const classify = item.componentClassify || '未分类';

      if (!classifyMap.has(classify)) {
        classifyMap.set(classify, {
          title: classify,
          key: `classify-${classify}`,
          id: item.id,
          children: []
        });
      }


      classifyMap.get(classify).children.push({
        title: item.name,
        key: item.identifier,
        id: item.id,
        data: item
      });
    });

    return Array.from(classifyMap.values());
  };

  // 获取树形组件列表
  const fetchData = async () => {
    const res: any = await getTreeComponents();

    if (res.code === 200) {
      const formattedData = formatTreeData(res.data);
      setTreeData(formattedData);
      setOriginalData(formattedData);

      const count = res.data.reduce((acc, item) => {
        if (item.testCount > 0) {
          acc.passed++;
        }
        else {
          acc.failed++;
        }
        return acc;
      }, { total: res.data.length, passed: 0, failed: 0 });
      getCount(count);
    }
  };

  // 处理节点选择
  const handleTreeSelect = (selectedKeys: any[], info: any) => {
    const selectedKey = selectedKeys[0];

    // 如果是父节点(分类节点),切换展开/收起状态
    if (selectedKey && selectedKey.startsWith('classify-')) {
      const isExpanded = expandedKeys.includes(selectedKey);
      if (isExpanded) {
        setExpandedKeys(expandedKeys.filter(key => key !== selectedKey));
      }
      else {
        setExpandedKeys([...expandedKeys, selectedKey]);
      }
    }
    else if (selectedKey) {
      const parentId = info.node.props.id;

      onNodeSelect(selectedKey, parentId);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <div className={styles['sidebar-container']}>
      <Input
        prefix={<IconSearch />}
        placeholder={'搜索'}
        value={searchValue}
        onChange={handleSearchChange}
      />
      <div className={styles['tree-wrapper']}>
        <Tree
          onSelect={handleTreeSelect}
          onExpand={(keys) => {
            setExpandedKeys(keys as string[]);
          }}
          expandedKeys={expandedKeys}
          treeData={treeData}
        >
        </Tree>
      </div>
    </div>
  );
};

export default SideBar;