import React, { useState, useEffect, useImperativeHandle } 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?: (key: string) => void;
  onTabClose?: (key: string) => void;
}

// 添加ref类型定义
export type NavBarRef = {
  deleteTabByKey: (key: string) => void;
};

const NavBar: React.ForwardRefRenderFunction<NavBarRef, NavBarProps> = ({
                                                                          selected,
                                                                          menuData,
                                                                          onTabChange,
                                                                          onTabClose
                                                                        }, ref) => {
  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 parentKey = selected.parentKey;
      const title = selected.title;
      const pathTitle = selected?.pathTitle || null;
      // 检查tab是否已存在
      const existingTab = tabs.find(tab => tab.key === key);

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

        setTabs(prev => [...prev, newTab]);
        setActiveTab(key);
      }
      else {
        // 如果tab已存在，激活它
        setActiveTab(key);
      }
    }
    else if (!selected?.path && tabs.length > 0) {
      // 如果没有选中的路径但有tabs存在，保持当前激活的tab
      // 这样可以避免在切换tab时意外清除activeTab
    }
  }, [selected, menuData]);

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

    // 如果删除的是当前激活的tab，激活下一个tab（如果存在）
    if (key === activeTab) {
      if (newTabs.length > 0) {
        // 尝试激活相邻的tab
        const currentIndex = tabs.findIndex(tab => tab.key === key);
        const nextIndex = currentIndex > 0 ? currentIndex - 1 : 0;
        const nextTab = newTabs[nextIndex];
        
        setActiveTab(nextTab.key);
        onTabChange?.(nextTab.key);
      } else {
        // 如果没有更多tabs，重置状态
        setActiveTab('');
        onTabChange?.('');
      }
    }

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

  // 提供给父组件调用的删除tab方法
  const deleteTabByKey = (key: string) => {
    handleDeleteTab(key);
  };

  // 暴露方法给父组件使用
  useImperativeHandle(ref, () => ({
    deleteTabByKey
  }));

  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.pathTitle || tab.title}
            >
            </TabPane>
          ))}
        </Tabs>
      ) : (
        <div style={{ height: 40, display: 'flex', alignItems: 'center', paddingLeft: 20 }}>
        </div>
      )}
    </div>
  );
};

export default React.forwardRef(NavBar);