import { useState } from 'react';
import { AuthProvider, useAuth } from './components/auth/AuthContext';
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';

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);

  // 如果未登录，显示登录/注册页面
  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} />;
      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-gray-50 flex flex-col overflow-hidden">
      <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-gray-400 hover:text-green-600",
            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-gray-50">
          <div className="p-6">
            {renderContent()}
          </div>
        </main>
      </div>
      <Toaster />
    </div>
  );
}

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