import React, { useState, useRef, useEffect } from 'react';
import { Link, useLocation } from 'react-router-dom';
import {
  FolderIcon,
  UserGroupIcon,
  CpuChipIcon,
  DocumentDuplicateIcon,
  WrenchScrewdriverIcon,
  SparklesIcon,
  ChevronDownIcon,
} from '@heroicons/react/24/outline';

// 导航项类型定义
interface NavItem {
  name: string;
  href?: string;
  icon: React.ComponentType<any>;
  description: string;
  children?: NavItem[];
}

const Navigation: React.FC = () => {
  const location = useLocation();
  const [openDropdown, setOpenDropdown] = useState<string | null>(null);
  const dropdownRef = useRef<HTMLDivElement>(null);

  // 点击外部关闭下拉菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setOpenDropdown(null);
      }
    };

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, []);

  const navItems: NavItem[] = [
    {
      name: '项目',
      href: '/',
      icon: FolderIcon,
      description: '管理项目和素材'
    },
    {
      name: '模特',
      href: '/models',
      icon: UserGroupIcon,
      description: '管理模特信息'
    },
    {
      name: '模板',
      href: '/templates',
      icon: DocumentDuplicateIcon,
      description: '管理剪映模板'
    },
    {
      name: '分类',
      href: '/ai-classification-settings',
      icon: CpuChipIcon,
      description: '管理AI视频分类规则'
    },
    {
      name: '穿搭',
      href: '/outfit',
      icon: SparklesIcon,
      description: 'AI穿搭方案推荐与素材检索'
    },
    {
      name: '工具',
      icon: WrenchScrewdriverIcon,
      href: '/tools',
      description: 'AI检索图片/数据清洗工具'
    }
  ];

  const isActive = (href: string) => {
    if (href === '/') {
      return location.pathname === '/';
    }

    // 特殊处理：工具页面只匹配 /tools 本身，不匹配子路径
    if (href === '/tools') {
      return location.pathname === '/tools';
    }

    // 特殊处理：项目页面匹配 /projects 和 /project/:id
    if (href === '/projects') {
      return location.pathname === '/projects' || location.pathname.startsWith('/project/');
    }

    // 其他路径使用 startsWith 匹配
    return location.pathname.startsWith(href);
  };

  // 检查下拉菜单项是否有激活的子项
  const hasActiveChild = (children: NavItem[]) => {
    return children.some(child => child.href && isActive(child.href));
  };

  // 切换下拉菜单
  const toggleDropdown = (itemName: string) => {
    setOpenDropdown(openDropdown === itemName ? null : itemName);
  };

  return (
    <nav className="bg-white/95 backdrop-blur-sm shadow-sm border-b border-gray-200/50 sticky top-0 z-50 flex-shrink-0">
      <div className="px-4 sm:px-2 lg:px-4">
        <div className="flex items-center justify-between h-16">
          {/* 增强的 Logo */}
          <div className="flex items-center">
            <div className="flex-shrink-0">
              <div className="flex items-center gap-2">
                <div className="w-8 h-8 bg-gradient-to-br from-primary-500 to-primary-600 rounded-lg flex items-center justify-center shadow-sm">
                  <span className="text-white font-bold text-sm">M</span>
                </div>
                <h1 className="text-xl font-bold bg-gradient-to-r from-gray-900 to-gray-700 bg-clip-text text-transparent">MixVideo</h1>
              </div>
            </div>
          </div>

          <div ref={dropdownRef}>
            <div className="ml-4 flex items-baseline space-x-2">
              {navItems.map((item) => {
                const Icon = item.icon;

                // 如果有子菜单，渲染下拉菜单
                if (item.children) {
                  const hasActive = hasActiveChild(item.children);
                  const isOpen = openDropdown === item.name;

                  return (
                    <div key={item.name} className="relative">
                      <button
                        onClick={() => toggleDropdown(item.name)}
                        className={`group flex items-center px-2 py-2 rounded-lg text-sm font-medium transition-all duration-200 relative overflow-hidden ${hasActive
                            ? 'bg-gradient-to-r from-primary-100 to-primary-200 text-primary-700 shadow-sm'
                            : 'text-gray-600 hover:text-gray-900 hover:bg-gradient-to-r hover:from-gray-50 hover:to-gray-100'
                          }`}
                        title={item.description}
                      >
                        {hasActive && (
                          <div className="absolute inset-0 bg-gradient-to-r from-primary-500/10 to-primary-600/10"></div>
                        )}
                        <Icon className={`mr-2 h-5 w-5 relative z-10 transition-all duration-200 ${hasActive ? 'text-primary-600' : 'text-gray-400 group-hover:text-gray-600 group-hover:scale-110'
                          }`} />
                        <span className="relative z-10">{item.name}</span>
                        <ChevronDownIcon className={`ml-1 h-4 w-4 relative z-10 transition-transform duration-200 ${isOpen ? 'rotate-180' : ''
                          } ${hasActive ? 'text-primary-600' : 'text-gray-400 group-hover:text-gray-600'}`} />
                      </button>

                      {/* 下拉菜单 */}
                      {isOpen && (
                        <div className="absolute top-full left-0 mt-1 w-56 bg-white rounded-lg shadow-lg border border-gray-200 py-1 z-50">
                          {item.children.map((child) => {
                            const ChildIcon = child.icon;
                            const childActive = child.href ? isActive(child.href) : false;

                            return (
                              <Link
                                key={child.name}
                                to={child.href || '#'}
                                className={`group flex items-center px-4 py-2 text-sm transition-all duration-200 ${childActive
                                    ? 'bg-primary-50 text-primary-700'
                                    : 'text-gray-700 hover:bg-gray-50 hover:text-gray-900'
                                  }`}
                                title={child.description}
                                onClick={() => setOpenDropdown(null)}
                              >
                                <ChildIcon className={`mr-3 h-4 w-4 transition-all duration-200 ${childActive ? 'text-primary-600' : 'text-gray-400 group-hover:text-gray-600'
                                  }`} />
                                <div>
                                  <div className="font-medium">{child.name}</div>
                                  <div className="text-xs text-gray-500 mt-0.5">{child.description}</div>
                                </div>
                              </Link>
                            );
                          })}
                        </div>
                      )}
                    </div>
                  );
                }

                // 普通导航项
                const active = item.href ? isActive(item.href) : false;

                return (
                  <Link
                    key={item.name}
                    to={item.href || '#'}
                    className={`group flex items-center px-2 py-2 rounded-lg text-sm font-medium transition-all duration-200 relative overflow-hidden ${active
                        ? 'bg-gradient-to-r from-primary-100 to-primary-200 text-primary-700 shadow-sm'
                        : 'text-gray-600 hover:text-gray-900 hover:bg-gradient-to-r hover:from-gray-50 hover:to-gray-100'
                      }`}
                    title={item.description}
                  >
                    {active && (
                      <div className="absolute inset-0 bg-gradient-to-r from-primary-500/10 to-primary-600/10"></div>
                    )}
                    <Icon className={`mr-2 h-5 w-5 relative z-10 transition-all duration-200 ${active ? 'text-primary-600' : 'text-gray-400 group-hover:text-gray-600 group-hover:scale-110'
                      }`} />
                    <span className="relative z-10">{item.name}</span>
                  </Link>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    </nav>
  );
};

export default Navigation;
