import React, { useState, useEffect } from 'react';
import { LoginPage } from './pages/LoginPage';
import { RegisterPage } from './pages/RegisterPage';
import { DevicesPage } from './pages/DevicesPage';
import { ConnectionsPage } from './pages/ConnectionsPage';
import { NodesPage } from './pages/NodesPage';
import { LogsPage } from './pages/LogsPage';
import { SettingsPage } from './pages/SettingsPage';

type Page =
  | 'login'
  | 'register'
  | 'devices'
  | 'connections'
  | 'nodes'
  | 'logs'
  | 'settings';

export function App() {
  const [currentPage, setCurrentPage] = useState<Page>('login');
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [user, setUser] = useState<any>(null);

  useEffect(() => {
    // 检查是否已登录
    window.electronAPI.getMe().then((res) => {
      if (res.success) {
        setIsLoggedIn(true);
        setUser(res.data);
        setCurrentPage('connections');
      }
    });
  }, []);

  if (!isLoggedIn) {
    if (currentPage === 'register') {
      return <RegisterPage onSwitchToLogin={() => setCurrentPage('login')} />;
    }
    return (
      <LoginPage
        onLoginSuccess={(userData) => {
          setIsLoggedIn(true);
          setUser(userData);
          setCurrentPage('connections');
        }}
        onSwitchToRegister={() => setCurrentPage('register')}
      />
    );
  }

  const navItems: { page: Page; label: string }[] = [
    { page: 'connections', label: '连接' },
    { page: 'devices', label: '设备' },
    { page: 'nodes', label: '节点' },
    { page: 'logs', label: '日志' },
    { page: 'settings', label: '设置' },
  ];

  return (
    <div className="app-layout">
      <aside className="sidebar">
        <div className="sidebar-header">
          <h2>🌐 组网工具</h2>
          <span className="user-email">{user?.email}</span>
        </div>
        <nav className="sidebar-nav">
          {navItems.map((item) => (
            <button
              key={item.page}
              className={`nav-btn ${currentPage === item.page ? 'active' : ''}`}
              onClick={() => setCurrentPage(item.page)}
            >
              {item.label}
            </button>
          ))}
        </nav>
        <div className="sidebar-footer">
          <button
            className="nav-btn logout-btn"
            onClick={() => {
              setIsLoggedIn(false);
              setUser(null);
              setCurrentPage('login');
              window.electronAPI.disconnectFromRelay();
            }}
          >
            退出登录
          </button>
        </div>
      </aside>
      <main className="main-content">
        {currentPage === 'connections' && <ConnectionsPage />}
        {currentPage === 'devices' && <DevicesPage />}
        {currentPage === 'nodes' && <NodesPage />}
        {currentPage === 'logs' && <LogsPage />}
        {currentPage === 'settings' && <SettingsPage />}
      </main>
    </div>
  );
}
