import { useEffect, useState } from 'react';
import { Routes, Route, Navigate, useLocation } from 'react-router-dom';
import { authService } from './services';
import { initLanguageFromStorage } from './i18n/utils';
import { i18nManager } from './i18n/manager';

// Page components
import Home from './pages/home';
import History from './pages/history';
import FriendsPhoto from './pages/friends-photo';
import Result from './pages/result';

// Bottom navigation component
import BottomNavigation from './components/BottomNavigation';

import './app.css';

function App() {
  const [isAuthenticated, setIsAuthenticated] = useState<boolean | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const location = useLocation();

  // Pages that don't need to show bottom navigation
  const hideBottomNavPages = ['/friends-photo', '/result'];

  useEffect(() => {
    const initApp = async () => {
      try {
        // Initialize internationalization
        await initLanguageFromStorage();
        await i18nManager.initializeApp();

        // Check login status, including OAuth 2.0 callback handling
        const isLoggedIn = await authService.checkLogin();
        setIsAuthenticated(isLoggedIn);

        if (!isLoggedIn) {
          console.log('User not logged in, preparing to redirect to login page');
          // Delay a bit before redirecting to let user see loading state
          setTimeout(() => {
            authService.login();
          }, 1000);
        } else {
          console.log('User already logged in');
        }
      } catch (error) {
        console.error('Application initialization failed:', error);
        setIsAuthenticated(false);
      } finally {
        setIsLoading(false);
      }
    };

    initApp();
  }, []);

  // Show loading state
  if (isLoading) {
    return (
      <div className="app-loading">
        <div className="loading-container">
          <div className="loading-spinner"></div>
          <div className="loading-text">Initializing application...</div>
        </div>
      </div>
    );
  }

  // If not authenticated, show login prompt
  if (isAuthenticated === false) {
    return (
      <div className="app-loading">
        <div className="loading-container">
          <div className="loading-spinner"></div>
          <div className="loading-text">Redirecting to login page...</div>
        </div>
      </div>
    );
  }

  return (
    <div className="app">
      <div className="app-content">
        <Routes>
          <Route path="/" element={<Navigate to="/home" replace />} />
          <Route path="/home" element={<Home />} />
          <Route path="/history" element={<History />} />
          <Route path="/friends-photo" element={<FriendsPhoto />} />
          <Route path="/result" element={<Result />} />
        </Routes>
      </div>
      {!hideBottomNavPages.includes(location.pathname) && <BottomNavigation />}
    </div>
  );
}

export default App;
