import React, { useState, useEffect } from 'react';
import { Tabs } from '@arco-design/web-react';
import styles from './style/navbar.module.less';
import { Selected } from '@/pages/ideContainer/types';

const TabPane = Tabs.TabPane;

interface NavBarProps {
  selected?: Selected;
  menuData?: any[];
  onTabChange?: (path: string) => void;
  onTabClose?: (path: string) => void;
}

const NavBar: React.FC<NavBarProps> = ({ selected, menuData, onTabChange, onTabClose }) => {
  const [tabs, setTabs] = useState<any[]>([]);
  const [activeTab, setActiveTab] = useState<string>('');

  // 根据菜单数据和路径查找菜单标题
  const findMenuTitle = (originData: Selected, menu: any[], path?: string): string => {
    if (!path) return '未知页面';

    for (const item of menu) {
      if (item.path === path && item.title === originData.title) {
        return item.title;
      }
      if (item.children) {
        const title = findMenuTitle(originData, item.children, path);
        if (title && title !== '未知页面') {
          return title;
        }
      }
    }

    return '未知页面';
  };


  // 当选中的菜单项变化时，添加新的tab
  useEffect(() => {
    if (selected?.path) {
      const path = selected.path;
      const key = selected.key;
      const title = selected.title;
      // 检查tab是否已存在
      const existingTab = tabs.find(tab => tab.key === key && tab.title === title);

      if (!existingTab) {
        // 创建新tab
        const title = menuData ? findMenuTitle(selected, menuData, path) : path;
        const newTab = {
          key: key,
          title: title,
          path: path
        };

        setTabs(prev => [...prev, newTab]);
        setActiveTab(key);
      }
      else {
        // 如果tab已存在，激活它
        setActiveTab(key);
      }
    }
  }, [selected, menuData]);

  const handleDeleteTab = (key: string) => {
    const newTabs = tabs.filter(tab => tab.key !== key);
    setTabs(newTabs);

    // 如果删除的是当前激活的tab，激活第一个tab（如果存在）
    if (key === activeTab && newTabs.length > 0) {
      setActiveTab(newTabs[0].key);
      onTabChange?.(newTabs[0].path);
    }
    else if (key === activeTab && newTabs.length === 0) {
      setActiveTab('');
      onTabChange?.('');
    }

    // 通知父组件tab已关闭
    onTabClose?.(key);
  };

  const handleTabChange = (key: string) => {
    setActiveTab(key);
    // 查找对应的tab并通知父组件
    const tab = tabs.find(t => t.key === key);
    if (tab) {
      onTabChange?.(tab.key);
    }
  };

  return (
    <div className={styles.navbar}>
      {tabs.length > 0 ? (
        <Tabs
          editable
          showAddButton={false}
          type="card-gutter"
          activeTab={activeTab}
          onDeleteTab={handleDeleteTab}
          onChange={handleTabChange}
        >
          {tabs.map(tab => (
            <TabPane
              destroyOnHide
              key={tab.key}
              title={tab.title}
            >
            </TabPane>
          ))}
        </Tabs>
      ) : (
        <div style={{ height: 40, display: 'flex', alignItems: 'center', paddingLeft: 20 }}>
          请选择左侧菜单项
        </div>
      )}
    </div>
  );
};

export default NavBar;