import { useState, useEffect } from 'react';
import { AuthProvider, useAuth } from './components/auth/AuthContext';
import { ThemeProvider } from './components/ThemeProvider';
import { Login } from './components/auth/Login';
import { Register } from './components/auth/Register';
import { Navigation } from './components/Navigation';
import { Sidebar } from './components/Sidebar';
import { cn } from './components/ui/utils';
import { MachineryManagement } from './components/dashboard/MachineryManagement';
import { FieldManagement } from './components/dashboard/FieldManagement';
import { OperationManagement } from './components/dashboard/OperationManagement';
import { AssetManagement } from './components/dashboard/AssetManagement';
import { AIModelSystem } from './components/dashboard/AIModelSystem';
import { IrrigationControl } from './components/dashboard/IrrigationControl';
import { ConfigManagement } from './components/dashboard/ConfigManagement';
import { Toaster } from './components/ui/sonner';
import {
  machineryMenus,
  fieldMenus,
  operationMenus,
  assetMenus,
  aiMenus,
  irrigationMenus,
  configMenus,
} from './types/navigation';
import { loadAMapScript, isAMapLoaded } from './lib/mapLoader';

function MainApp() {
  const { authState } = useAuth();
  const [activeTab, setActiveTab] = useState('machinery');
  const [activePath, setActivePath] = useState('/machinery/archive/entry');
  const [showRegister, setShowRegister] = useState(false);
  const [sidebarCollapsed, setSidebarCollapsed] = useState(false);

  // 预加载高德地图SDK
  useEffect(() => {
    // 检查是否已加载
    if (isAMapLoaded()) {
      console.log('✅ 高德地图SDK已就绪');
      return;
    }

    // 异步加载高德地图SDK，不阻塞应用启动
    loadAMapScript()
      .then((AMap) => {
        if (AMap) {
          console.log('✅ 高德地图SDK加载成功');
          console.log('📍 版本:', AMap.version);
        } else {
          console.log('💡 使用占位地图模式（功能完整）');
          console.log('💡 如需真实地图，请在 /lib/mapLoader.ts 中配置高德地图Key');
        }
      })
      .catch((error) => {
        console.error('❌ 高德地图SDK加载失败:', error);
        console.log('💡 将使用占位地图模式');
      });
  }, []);

  // 自动初始化多角色测试数据（仅在登录后执行一次）
  useEffect(() => {
    if (authState.isAuthenticated && authState.user) {
      try {
        // 获取当前用户资料
        let profile = localStorage.getItem('smart_agriculture_user_profile');
        
        if (!profile) {
          // 如果没有用户资料，创建基础资料
          const newProfile = {
            id: authState.user.id || 'user-1',
            username: authState.user.username || 'admin',
            name: authState.user.realName || authState.user.username || '系统管理员',
            realName: authState.user.realName || '系统管理员',
            phone: authState.user.phone || '13800138000',
            email: authState.user.email || '',
            enterpriseName: authState.user.enterpriseName || '示例企业',
            department: authState.user.department || '技术部',
            // 添加5个测试角色
            roleIds: ['role-1', 'role-2', 'role-3', 'role-4', 'role-5'],
            roleNames: ['超级管理员', '企业管理员', '操作员', '查看者', '技术员'],
          };
          localStorage.setItem('smart_agriculture_user_profile', JSON.stringify(newProfile));
          console.log('✅ 已自动初始化多角色测试数据');
          console.log('🔄 角色列表:', newProfile.roleNames);
        } else {
          // 如果有用户资料，检查是否已有多个角色
          const profileData = JSON.parse(profile);
          const roleCount = (profileData.roleIds || []).length;
          
          if (roleCount <= 1) {
            // 只有一个或没有角色，自动添加多个测试角色
            profileData.roleIds = ['role-1', 'role-2', 'role-3', 'role-4', 'role-5'];
            profileData.roleNames = ['超级管理员', '企业管理员', '操作员', '查看者', '技术员'];
            localStorage.setItem('smart_agriculture_user_profile', JSON.stringify(profileData));
            console.log('✅ 已自动添加多角色测试数据');
            console.log('🔄 角色列表:', profileData.roleNames);
          } else {
            console.log('✅ 检测到已有', roleCount, '个角色，角色切换功能已启用');
            console.log('🔄 角色列表:', profileData.roleNames);
          }
        }
      } catch (error) {
        console.error('❌ 初始化角色数据失败:', error);
      }
    }
  }, [authState.isAuthenticated, authState.user]);

  // 如果未登录，显示登录/注册页面
  if (!authState.isAuthenticated) {
    return showRegister ? (
      <Register onBackToLogin={() => setShowRegister(false)} />
    ) : (
      <Login onRegisterClick={() => setShowRegister(true)} />
    );
  }

  const getMenusForTab = (tabId?: string) => {
    const tab = tabId || activeTab;
    switch (tab) {
      case 'machinery': return machineryMenus;
      case 'field': return fieldMenus;
      case 'operation': return operationMenus;
      case 'asset': return assetMenus;
      case 'ai-model': return aiMenus;
      case 'irrigation': return irrigationMenus;
      case 'config': return configMenus;
      default: return machineryMenus;
    }
  };

  const handleTabChange = (tab: string) => {
    setActiveTab(tab);
    // 切换子系统时，默认选中第一个菜单项
    const menus = getMenusForTab(tab);
    const firstPath = menus[0]?.children?.[0]?.path;
    if (firstPath) {
      setActivePath(firstPath);
    }
  };

  const handleMessageClick = () => {
    setActiveTab('config');
    setActivePath('/config/message/log');
  };

  const handleProfileClick = () => {
    setActiveTab('config');
    setActivePath('/config/profile/info');
  };

  const renderContent = () => {
    switch (activeTab) {
      case 'machinery':
        return <MachineryManagement activePath={activePath} />;
      case 'field':
        return <FieldManagement activePath={activePath} />;
      case 'operation':
        return <OperationManagement activePath={activePath} />;
      case 'asset':
        return <AssetManagement activePath={activePath} onNavigate={setActivePath} />;
      case 'ai-model':
        return <AIModelSystem activePath={activePath} />;
      case 'irrigation':
        return <IrrigationControl activePath={activePath} />;
      case 'config':
        return <ConfigManagement activePath={activePath} />;
      default:
        return <MachineryManagement activePath={activePath} />;
    }
  };

  return (
    <div className="h-screen bg-background flex flex-col overflow-hidden transition-colors">
      <Navigation 
        activeTab={activeTab} 
        onTabChange={handleTabChange}
        onMessageClick={handleMessageClick}
        onProfileClick={handleProfileClick}
      />
      <div className="flex flex-1 overflow-hidden relative">
        <Sidebar
          menus={getMenusForTab()}
          activePath={activePath}
          onNavigate={setActivePath}
          collapsed={sidebarCollapsed}
          onCollapsedChange={setSidebarCollapsed}
        />
        
        {/* 收起/展开按钮 - 紧贴侧边栏右侧 */}
        <button
          onClick={() => setSidebarCollapsed(!sidebarCollapsed)}
          className={cn(
            "absolute top-2 z-10 transition-all duration-300",
            "text-muted-foreground hover:text-primary",
            sidebarCollapsed ? "left-16" : "left-64"
          )}
          title={sidebarCollapsed ? "展开菜单" : "收起菜单"}
        >
          {sidebarCollapsed ? (
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M9 5l7 7-7 7" />
            </svg>
          ) : (
            <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M15 19l-7-7 7-7" />
            </svg>
          )}
        </button>
        
        <main className="flex-1 overflow-y-auto bg-background">
          <div className="p-6">
            {renderContent()}
          </div>
        </main>
      </div>
      <Toaster />
    </div>
  );
}

export default function App() {
  return (
    <ThemeProvider>
      <AuthProvider>
        <MainApp />
      </AuthProvider>
    </ThemeProvider>
  );
}
