import * as React from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useLayoutStore } from '../store';
import './sidebar.scss';
import { Star, Database, Key, ClipboardCheck, Book, Notebook, FolderPlus, PlusCircle } from 'lucide-react';

interface NavItem {
    key: string;
    icon: string;
    label: string;
    path: string;
}

// icon 名称到 lucide 组件的映射
const iconMap: Record<string, React.ComponentType<any>> = {
    'widget': Star, // 临时用 Star 替代
    'book': Book,
    'star': Star,
    'notebook': Notebook,
    'gallery': FolderPlus,
    'plus-circle': PlusCircle,
    'database': Database,
    'key': Key,
    'clipboard-check': ClipboardCheck,
};

const Sidebar: React.FC = () => {
    const navigate = useNavigate();
    const location = useLocation();
    const { collapsed } = useLayoutStore();

    // 应用矩阵菜单
    const appMenuItems: NavItem[] = [
        { key: '/appCenter', icon: 'widget', label: '全部 RAG 应用', path: '/appCenter' },
        { key: '/appCenter/category?category=professional', icon: 'book', label: '专业知识', path: '/appCenter/category?category=professional' },
        { key: '/appCenter/category?category=functional', icon: 'star', label: '职能管理', path: '/appCenter/category?category=functional' },
        { key: '/appCenter/category?category=project', icon: 'notebook', label: '项目级应用', path: '/appCenter/category?category=project' },
        { key: '/otherApps', icon: 'gallery', label: '其他非 RAG 应用', path: '/otherApps' },
    ];

    // 管理控制台菜单
    const adminMenuItems: NavItem[] = [
        { key: '/appCenter/questionAnswer', icon: 'plus-circle', label: '我创建的应用', path: '/appCenter/questionAnswer' },
        { key: '/knowledge/knowledgeLib', icon: 'database', label: '知识库管理', path: '/knowledge/knowledgeLib' },
        { key: '/system/apiKey', icon: 'key', label: 'API 管理', path: '/system/apiKey' },
        { key: '/system/audit', icon: 'clipboard-check', label: '应用审核', path: '/system/audit' },
    ];

    // 检查是否为当前激活的路由（支持带参数的路由和子路由）
    const isActive = (itemPath: string, currentPath: string, currentSearch: string, matchSubRoutes: boolean = false) => {
        // 完整路径比较（包括 query 参数）
        const itemUrl = new URL(itemPath, 'http://localhost');
        const currentUrl = new URL(currentPath + (currentSearch ? '?' + currentSearch : ''), 'http://localhost');

        // 精确匹配（包括 query 参数）
        if (itemUrl.pathname === currentUrl.pathname &&
            itemUrl.searchParams.get('category') === currentUrl.searchParams.get('category')) {
            return true;
        }

        // 子路由匹配（仅当 matchSubRoutes=true 时启用）
        // 如 /appCenter/questionAnswer/create 匹配 /appCenter/questionAnswer
        if (matchSubRoutes && currentUrl.pathname.startsWith(itemUrl.pathname + '/')) {
            return true;
        }

        return false;
    };

    const handleNavClick = (path: string) => {
        console.log('导航到:', path);
        navigate(path);
    };

    return (
        <aside className={`sidebar ${collapsed ? 'collapsed' : ''}`}>
            <div className='sidebar-content'>
                {/* 应用矩阵 */}
                <div>
                    <h3 className='section-title'>应用矩阵</h3>
                    <nav className='nav-menu'>
                        {appMenuItems.map((item) => {
                            const IconComponent = iconMap[item.icon] || Star;
                            return (
                                <button
                                    key={item.key}
                                    className={`nav-item ${isActive(item.path, location.pathname, location.search, false) ? 'active' : ''}`}
                                    onClick={() => handleNavClick(item.path)}
                                >
                                    <IconComponent size={18} />
                                    <span>{item.label}</span>
                                </button>
                            );
                        })}
                    </nav>
                </div>

                {/* 管理控制台 */}
                <div>
                    <h3 className='section-title'>管理控制台</h3>
                    <nav className='nav-menu'>
                        {adminMenuItems.map((item) => {
                            const IconComponent = iconMap[item.icon] || Star;
                            return (
                                <button
                                    key={item.key}
                                    className={`nav-item ${isActive(item.path, location.pathname, location.search, true) ? 'active' : ''}`}
                                    onClick={() => handleNavClick(item.path)}
                                >
                                    <IconComponent size={18} />
                                    <span>{item.label}</span>
                                </button>
                            );
                        })}
                    </nav>
                </div>
            </div>
        </aside>
    );
};

export default Sidebar;
