import * as React from 'react';
import { Layout, Menu, Button } from 'antd';
import {
  RobotOutlined,
  ReadOutlined,
  FileSearchOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  CheckSquareOutlined
} from '@ant-design/icons';
import { JSX } from 'react/jsx-runtime';
import LocalStorage from '@/LocalStorage';
import useRouteStore from '@/store/route';
import {
  useNavigate
} from 'react-router-dom';
const {
  state,
  useMenuFromRoutes
} = useRouteStore;

const Sider = Layout.Sider;

interface MenuItem {
  key: string;
  icon: JSX.Element;
  label: string;
  onClick?: () => void;
}

interface Props {
  selectedKey: string,
  onChangeSelectedKey: (item: any) => void,
  openKeys: string[],
  onOpenChange: (openKeys: string[]) => void,
  collapsed: boolean,
  onClickCollapsed: () => void,
  menuType: number; // 新增 prop
  ref1: React.RefObject<any>;
  ref3?: React.RefObject<any>;
  ref5?: React.RefObject<any>;
};

const Nav: React.FC<Props> = (props: Props) => {
  const router = useNavigate();
  const {
    selectedKey,
    onChangeSelectedKey,
    openKeys,
    onOpenChange,
    collapsed,
    onClickCollapsed,
    menuType,
    ref1,
    ref3,
    ref5
  } = props;

  const flagMenu = useMenuFromRoutes(state.constantRoutes)
  const dsItems: MenuItem[] = [
    ...flagMenu
  ]
  const items = dsItems;
  const processItems = (list: any[]): any[] => {
    return list.map((it: any) => {
      const newItem = { ...it };
      // 先处理 children（如果有）
      if (Array.isArray(it.children) && it.children.length > 0) {
        newItem.children = processItems(it.children);
      }
      // 提取 label 文本（尽量兼容多种 label 结构）
      let labelText: any = undefined;
      if (typeof it.label === 'string') {
        labelText = it.label;
      } else if (it.label && it.label.props) {
        // 如果是 React 节点，尝试读取 children 文本
        const children = it.label.props.children;
        if (typeof children === 'string') {
          labelText = children;
        } else if (Array.isArray(children)) {
          // 取第一个字符串子项
          const firstText = children.find((c: any) => typeof c === 'string');
          labelText = firstText;
        }
      }

      // 只在匹配到的项上包裹 ref（匹配 key 或 label 文案）
      if (it.key === '/knowledge/knowledgeLib' || labelText === '知识库') {
        // 标记该 label，稍后用 DOM 查找到对应的 li 并赋值给 ref1
        newItem.label = <span data-tour-target="knowledge" style={{ display: 'inline-block', width: '200px' }}>{it.label}</span>;
      }
      // 标记应用中心菜单项
      if (it.key === '/appCenter' || labelText === '应用中心') {
        // 标记该 label，稍后用 DOM 查找到对应的 li 并赋值给 ref3
        newItem.label = <span data-tour-target="app-center" style={{ display: 'inline-block', width: '200px' }}>{it.label}</span>;
      }
      // 标记"我创建的应用"子菜单项
      if (it.key === '/appCenter/questionAnswer' || labelText === '我创建的应用') {
        // 标记该 label，稍后用 DOM 查找到对应的 li 并赋值给 ref5
        newItem.label = <span data-tour-target="my-apps" style={{ display: 'inline-block', width: '200px' }}>{it.label}</span>;
      }
      return newItem;
    });
  };

  const menuItems = processItems(items);

  // 将标记的 label 元素的最近 li 父节点赋值给外部传入的 ref1
  React.useEffect(() => {
    try {
      if (!ref1) return;
      const container = document.querySelector('.nav-menu');
      if (!container) return;
      const target = container.querySelector('[data-tour-target="knowledge"]');
      if (target) {
        const li = target.closest('li');
        if (li) {
          try {
            (ref1 as React.MutableRefObject<any>).current = li;
          } catch (e) {
            // ignore
          }
        }
      }
    } catch (e) {
      // ignore
    }
  }, [menuItems, ref1]);

  // 将标记的应用中心菜单 label 元素的最近 li 父节点赋值给外部传入的 ref3
  React.useEffect(() => {
    try {
      if (!ref3) return;
      const container = document.querySelector('.nav-menu');
      if (!container) return;
      const target = container.querySelector('[data-tour-target="app-center"]');
      if (target) {
        const li = target.closest('li');
        if (li) {
          try {
            (ref3 as React.MutableRefObject<any>).current = li;
          } catch (e) {
            // ignore
          }
        }
      }
    } catch (e) {
      // ignore
    }
  }, [menuItems, ref3]);

  // 将标记的"我创建的应用"子菜单 label 元素的最近 li 父节点赋值给外部传入的 ref5
  React.useEffect(() => {
    try {
      if (!ref5) return;
      const container = document.querySelector('.nav-menu');
      if (!container) return;
      const target = container.querySelector('[data-tour-target="my-apps"]');
      if (target) {
        const li = target.closest('li');
        if (li) {
          try {
            (ref5 as React.MutableRefObject<any>).current = li;
          } catch (e) {
            // ignore
          }
        }
      }
    } catch (e) {
      // ignore
    }
  }, [menuItems, ref5]);

  return (
    <Sider
      className='nav'
      collapsed={collapsed}
    >
      <div className='nav-menu'>
        <Menu
          mode='inline'
          selectedKeys={[selectedKey]}
          onSelect={(item) => {
            onChangeSelectedKey(item);
          }}
          openKeys={openKeys}
          onOpenChange={(keys) => {
            // 点击菜单，收起其他展开的所有菜单
            const latestOpenKey = keys.find((key) => openKeys.indexOf(key) === - 1);
            onOpenChange(latestOpenKey ? [latestOpenKey] : []);
          }}
          // theme={}
          items={menuItems}
        />
      </div>
      <div className='nav-bottom'>
        <Button type='primary' onClick={onClickCollapsed}>
          {collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
        </Button>
      </div>
    </Sider>
  );
};

export default Nav;