import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import apiClient from './utils/apiClient';
import { buildApiUrl, API_ENDPOINTS } from './config/api';
import HomePage from './pages/HomePage';
import Dashboard from './pages/Dashboard';
import MeetingDetails from './pages/MeetingDetails';
import CreateMeeting from './pages/CreateMeeting';
import EditMeeting from './pages/EditMeeting';
import AdminManagement from './pages/AdminManagement';
import KnowledgeBasePage from './pages/KnowledgeBasePage';
import './App.css';

function App() {
  const [user, setUser] = useState(null);
  const [isLoading, setIsLoading] = useState(true);

  // Load user from localStorage on app start
  useEffect(() => {
    const savedUser = localStorage.getItem('iMeetingUser');
    console.log('Saved user from localStorage:', savedUser);
    if (savedUser) {
      try {
        const parsedUser = JSON.parse(savedUser);
        console.log('Parsed user:', parsedUser);
        setUser(parsedUser);
      } catch (error) {
        console.error('Error parsing saved user:', error);
        localStorage.removeItem('iMeetingUser');
      }
    }
    setIsLoading(false);
  }, []);

  const handleLogin = (userData) => {
    setUser(userData);
    localStorage.setItem('iMeetingUser', JSON.stringify(userData));
  };

  const handleLogout = async () => {
    try {
      // 调用后端登出API撤销token
      await apiClient.post(buildApiUrl(API_ENDPOINTS.AUTH.LOGOUT));
    } catch (error) {
      console.error('Logout API error:', error);
      // 即使API调用失败也继续登出流程
    } finally {
      // 清除本地状态和存储
      setUser(null);
      localStorage.removeItem('iMeetingUser');
    }
  };

  if (isLoading) {
    return (
      <div className="app-loading">
        <div className="loading-spinner"></div>
        <p>加载中...</p>
      </div>
    );
  }

  return (
    <Router>
      <div className="app">
        <Routes>
          <Route path="/" element={
            user ? <Navigate to="/dashboard" /> : <HomePage onLogin={handleLogin} />
          } />
          <Route path="/dashboard" element={
            user ? <Dashboard user={user} onLogout={handleLogout} /> : <Navigate to="/" />
          } />
          <Route path="/meetings/:meeting_id" element={
            user ? <MeetingDetails user={user} /> : <Navigate to="/" />
          } />
          <Route path="/meetings/create" element={
            user ? <CreateMeeting user={user} /> : <Navigate to="/" />
          } />
          <Route path="/meetings/edit/:meeting_id" element={
            user ? <EditMeeting user={user} /> : <Navigate to="/" />
          } />
          <Route path="/admin/management" element={
            user && user.role_id === 1 ? <AdminManagement user={user} /> : <Navigate to="/dashboard" />
          } />
          <Route path="/knowledge-base" element={
            user ? <KnowledgeBasePage user={user} /> : <Navigate to="/" />
          } />
        </Routes>
      </div>
    </Router>
  );
}

export default App;