'use client';

import { useRouter, usePathname } from 'next/navigation';
import { useState, useEffect, useRef } from 'react';
import { useTranslation } from '@/hooks/useTranslation';
import { useSidebar } from '@/hooks/useSidebar';
import { getNavigationConfig } from '@/config/navigation';
import { useFilteredNavigation } from '@/hooks/useFilteredNavigation';
import { getEnvBannerVariant } from '@/lib/env-banner';

export function Sidebar() {
  const router = useRouter();
  const pathname = usePathname();
  const { t } = useTranslation();
  const { collapsed, userPreference, setCollapsed } = useSidebar();
  const envBannerVariant = getEnvBannerVariant();
  const [expandedMenus, setExpandedMenus] = useState<string[]>(['organization']); // 默认展开组织架构
  const [mounted, setMounted] = useState(false);
  const [hoveredTooltip, setHoveredTooltip] = useState<{
    label: string;
    x: number;
    y: number;
  } | null>(null);
  const showTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const hideTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

  // 定义图标（必须在所有 hooks 之后，条件渲染之前）
  const icons = {
    dashboard: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 5a1 1 0 011-1h4a1 1 0 011 1v7a1 1 0 01-1 1H5a1 1 0 01-1-1V5zM14 5a1 1 0 011-1h4a1 1 0 011 1v3a1 1 0 01-1 1h-4a1 1 0 01-1-1V5zM4 16a1 1 0 011-1h4a1 1 0 011 1v3a1 1 0 01-1 1H5a1 1 0 01-1-1v-3zM14 12a1 1 0 011-1h4a1 1 0 011 1v7a1 1 0 01-1 1h-4a1 1 0 01-1-1v-7z" />
      </svg>
    ),
    organization: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 21V5a2 2 0 00-2-2H7a2 2 0 00-2 2v16m14 0h2m-2 0h-5m-9 0H3m2 0h5M9 7h1m-1 4h1m4-4h1m-1 4h1m-5 10v-5a1 1 0 011-1h2a1 1 0 011 1v5m-4 0h4" />
      </svg>
    ),
    syncCenter: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
      </svg>
    ),
    approvals: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
      </svg>
    ),
    smartHr: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
      </svg>
    ),
    workRecord: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
      </svg>
    ),
    automation: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
      </svg>
    ),
    parts: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4" />
      </svg>
    ),
    forms: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
      </svg>
    ),
    feedback: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
      </svg>
    ),
    tickets: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 5v2m0 4v2m0 4v2M5 5a2 2 0 00-2 2v3a2 2 0 110 4v3a2 2 0 002 2h14a2 2 0 002-2v-3a2 2 0 110-4V7a2 2 0 00-2-2H5z" />
      </svg>
    ),
    knowledgeBase: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 6c-2.761 0-5 1.343-5 3v9a3 3 0 003 3h6a3 3 0 003-3V9c0-1.657-2.239-3-5-3z" />
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 9h10" />
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 13h10" />
      </svg>
    ),
    audit: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-6 9l2 2 4-4" />
      </svg>
    ),
    logs: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h7" />
      </svg>
    ),
    performance: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
      </svg>
    ),
    devtracker: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12h6m-6 4h6m-7 5h8a2 2 0 002-2V7a2 2 0 00-2-2h-1l-1-2H9L8 5H7a2 2 0 00-2 2v12a2 2 0 002 2z" />
      </svg>
    ),
    meetingAttendance: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V5m8 2V5M3 9h18M5 5h14a2 2 0 012 2v12a2 2 0 01-2 2H5a2 2 0 01-2-2V7a2 2 0 012-2zm5 7l2 2 4-4" />
      </svg>
    ),
    robotManager: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 3v2m6-2v2M12 1v2M8 7h8a2 2 0 012 2v4a2 2 0 01-2 2H8a2 2 0 01-2-2V9a2 2 0 012-2zm1 3h.01M15 10h.01M9 17l1.5 4M15 17l-1.5 4M12 15v2" />
      </svg>
    ),
    opsCenter: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 17v-2a4 4 0 014-4h4M9 17H5a2 2 0 01-2-2V7a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-4M9 17v4m6-4v4m-3-12h.01" />
      </svg>
    ),
    iamAdmin: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
      </svg>
    ),
    internalApps: (
      <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13 10V3L4 14h7v7l9-11h-7z" />
      </svg>
    ),
  };

  // 获取导航配置并根据权限过滤（必须在所有 hooks 之后，条件渲染之前）
  const allNavItems = getNavigationConfig(t, icons);
  const navItems = useFilteredNavigation(allNavItems);

  useEffect(() => {
    setMounted(true);
  }, []);

  useEffect(() => {
    return () => {
      if (showTimerRef.current) clearTimeout(showTimerRef.current);
      if (hideTimerRef.current) clearTimeout(hideTimerRef.current);
    };
  }, []);

  useEffect(() => {
    if (!collapsed) {
      setHoveredTooltip(null);
    }
  }, [collapsed]);

  // 当直接访问具体应用页面时，自动折叠侧边栏（仅当用户未手动设置偏好时）
  useEffect(() => {
    if (!mounted) return;

    // 🔍 调试日志
    console.log('[Sidebar] Route changed:', {
      pathname,
      userPreference,
      currentCollapsed: collapsed
    });

    // 如果用户已手动设置过偏好，则尊重用户选择，不再自动折叠
    if (userPreference !== null) {
      console.log('[Sidebar] User preference detected, skipping auto-collapse');
      return;
    }

    // 概览页面保持侧边栏展开
    if (pathname === '/overview' || pathname === '/') {
      return;
    }

    // 检查是否是具体应用页面（非概览页）
    const isAppPage = pathname !== '/overview' && 
                      pathname !== '/' && 
                      pathname !== '/login';

    if (isAppPage) {
      console.log('[Sidebar] Auto-collapsing sidebar (no user preference)');
      // 自动折叠侧边栏（非用户操作，不记录偏好）
      setCollapsed(true, false);
    }
  }, [pathname, mounted, userPreference, setCollapsed, collapsed]);

  // 防止 hydration 错误：在客户端挂载前显示骨架屏
  if (!mounted) {
    return (
      <div className="w-64 bg-white h-full flex flex-col" style={{ borderRight: '1px solid #e8e8e8' }}>
        <div className="h-16 flex items-center px-4" style={{ borderBottom: '1px solid #e8e8e8' }}>
          <div className="h-8 w-32 bg-gray-200 animate-pulse rounded"></div>
        </div>
        <div className="flex-1 py-4">
          {[1, 2, 3, 4, 5].map((i) => (
            <div key={i} className="px-4 py-3">
              <div className="h-5 bg-gray-200 animate-pulse rounded"></div>
            </div>
          ))}
        </div>
      </div>
    );
  }

  const toggleMenu = (path: string) => {
    setExpandedMenus(prev => 
      prev.includes(path) 
        ? prev.filter(p => p !== path)
        : [...prev, path]
    );
  };

  const showCollapsedTooltip = (
    label: string,
    rect: { right: number; top: number; height: number }
  ) => {
    if (!collapsed) return;

    if (hideTimerRef.current) {
      clearTimeout(hideTimerRef.current);
      hideTimerRef.current = null;
    }

    if (showTimerRef.current) {
      clearTimeout(showTimerRef.current);
    }

    showTimerRef.current = setTimeout(() => {
      setHoveredTooltip({
        label,
        x: rect.right + 10,
        y: rect.top + rect.height / 2,
      });
    }, 120);
  };

  const hideCollapsedTooltip = (label: string) => {
    if (!collapsed) return;

    if (showTimerRef.current) {
      clearTimeout(showTimerRef.current);
      showTimerRef.current = null;
    }

    if (hideTimerRef.current) {
      clearTimeout(hideTimerRef.current);
    }

    hideTimerRef.current = setTimeout(() => {
      setHoveredTooltip((prev) => (prev?.label === label ? null : prev));
    }, 80);
  };

  const sidebarTop = envBannerVariant === 'uat' ? '92px' : '64px';

  return (
    <div
      className={`${collapsed ? 'w-16' : 'w-64'} bg-white flex flex-col fixed left-0 bottom-0 transition-all duration-200 border-r z-40`}
      style={{ borderColor: 'var(--border-color)', top: sidebarTop }}
    >

      {/* Navigation Items - 飞书风格 */}
      <nav className="flex-1 py-2 px-2 space-y-1 overflow-y-auto scrollbar-custom">
        {navItems.map((item) => {
          const isActive = pathname === item.path || pathname.startsWith(item.path + '/');
          const isExpanded = expandedMenus.includes(item.path);
          const hasSubItems = item.subItems && item.subItems.length > 0;
          
          return (
            <div key={item.path}>
              <button
                onClick={() => {
                  if (hasSubItems) {
                    if (collapsed) {
                      // 折叠状态：展开侧边栏并展开菜单（标记为用户操作）
                      setCollapsed(false, true);
                      if (!isExpanded) {
                        toggleMenu(item.path);
                      }
                    } else {
                      // 展开状态：只切换子菜单展开/折叠状态（不自动导航）
                      toggleMenu(item.path);
                    }
                  } else {
                    // 无子菜单：只导航，不改变折叠状态（尊重用户偏好）
                    router.push(item.path);
                    // 不再强制收起侧边栏
                  }
                }}
                className={`w-full flex items-center px-3 py-2 rounded-lg transition-all duration-150 ${
                  collapsed ? 'justify-center' : 'justify-between'
                }`}
                aria-label={item.name}
                style={{
                  background: isActive ? 'var(--lark-blue-light)' : 'transparent',
                  color: isActive ? 'var(--lark-blue)' : 'var(--text-secondary)',
                }}
                onMouseEnter={(e) => {
                  if (collapsed) {
                    const rect = e.currentTarget.getBoundingClientRect();
                    showCollapsedTooltip(item.name, rect);
                  }
                  if (!isActive) {
                    e.currentTarget.style.background = 'var(--bg-tertiary)';
                  }
                }}
                onMouseLeave={(e) => {
                  if (collapsed) {
                    hideCollapsedTooltip(item.name);
                  }
                  if (!isActive) {
                    e.currentTarget.style.background = 'transparent';
                  }
                }}
                onFocus={(e) => {
                  if (collapsed) {
                    const rect = e.currentTarget.getBoundingClientRect();
                    showCollapsedTooltip(item.name, rect);
                  }
                }}
                onBlur={() => {
                  if (collapsed) {
                    hideCollapsedTooltip(item.name);
                  }
                }}
              >
                <div className={`flex items-center ${collapsed ? '' : 'space-x-3'}`}>
                  <div className="flex-shrink-0">
                    {item.icon}
                  </div>
                  {!collapsed && (
                    <span className="text-sm font-medium truncate">
                      {item.name}
                    </span>
                  )}
                </div>
                {!collapsed && hasSubItems && (
                  <svg 
                    className={`w-4 h-4 transition-transform duration-200 ${isExpanded ? 'rotate-180' : ''}`}
                    fill="none" 
                    stroke="currentColor" 
                    viewBox="0 0 24 24"
                  >
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
                  </svg>
                )}
              </button>
              
              {/* Sub-menu items - 展开状态 */}
              {!collapsed && hasSubItems && isExpanded && (
                <div className="mt-1 ml-8 space-y-1">
                  {item.subItems!.map((subItem) => {
                    const isSubActive = pathname === subItem.path || pathname.startsWith(subItem.path + '/');
                    
                    return (
                      <button
                        key={subItem.path}
                        onClick={() => {
                          router.push(subItem.path);
                          // 不再强制收起侧边栏，尊重用户偏好
                        }}
                        className={`w-full flex items-center px-3 py-2 rounded-lg transition-all duration-150 text-sm ${
                          isSubActive ? 'font-medium' : ''
                        }`}
                        style={{
                          background: isSubActive ? 'var(--lark-blue-light)' : 'transparent',
                          color: isSubActive ? 'var(--lark-blue)' : 'var(--text-tertiary)',
                        }}
                        onMouseEnter={(e) => {
                          if (!isSubActive) {
                            e.currentTarget.style.background = 'var(--bg-tertiary)';
                          }
                        }}
                        onMouseLeave={(e) => {
                          if (!isSubActive) {
                            e.currentTarget.style.background = 'transparent';
                          }
                        }}
                      >
                        {subItem.name}
                      </button>
                    );
                  })}
                </div>
              )}

            </div>
          );
        })}
      </nav>

      {/* Collapse Button - 飞书风格 */}
      <div className="p-3 border-t" style={{ borderColor: 'var(--border-color)' }}>
        <button
          onClick={() => {
            console.log('[Sidebar] User clicked collapse button, current state:', collapsed);
            setCollapsed(!collapsed, true); // 标记为用户操作
          }}
          className="w-full flex items-center justify-center px-3 py-2 rounded-lg transition-all duration-150 text-sm hover:bg-gray-100"
          style={{ 
            color: 'var(--text-secondary)',
          }}
          title={collapsed ? t.nav.sidebar.expandMenu : t.nav.sidebar.collapseMenu}
        >
          <svg 
            className={`w-5 h-5 transition-transform duration-200 ${collapsed ? 'rotate-180' : ''}`}
            fill="none" 
            stroke="currentColor" 
            viewBox="0 0 24 24"
          >
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 19l-7-7 7-7m8 14l-7-7 7-7" />
          </svg>
          {!collapsed && <span className="ml-2">{t.nav.sidebar.collapseMenu}</span>}
        </button>
      </div>

      {/* 折叠态悬浮名称（全局浮层，避免被滚动容器裁剪） */}
      {collapsed && hoveredTooltip && (
        <div
          role="tooltip"
          className="pointer-events-none fixed z-[90] -translate-y-1/2 whitespace-nowrap rounded-md px-2.5 py-1.5 text-xs font-medium"
          style={{
            left: `${hoveredTooltip.x}px`,
            top: `${hoveredTooltip.y}px`,
            backgroundColor: '#1f2329',
            color: '#ffffff',
            boxShadow: '0 8px 24px rgba(31, 35, 41, 0.28)',
          }}
        >
          <div
            className="absolute top-1/2 h-2 w-2 -translate-y-1/2 rotate-45"
            style={{
              left: '-5px',
              backgroundColor: '#1f2329',
            }}
          />
          {hoveredTooltip.label}
        </div>
      )}
    </div>
  );
}
