import React, { useState } from 'react';
import { AuthProvider, useAuth } from './contexts/AuthContext';
import { Sidebar } from './components/layout/Sidebar';
import { Header } from './components/layout/Header';
import { DashboardPage } from './pages/DashboardPage';
import { UsersPage } from './pages/UsersPage';
import { WorkAllocationPage } from './pages/WorkAllocationPage';
import { AttendancePage } from './pages/AttendancePage';
import { RatesPage } from './pages/RatesPage';
import { EmployeeSwapPage } from './pages/EmployeeSwapPage';
import { LoginPage } from './pages/LoginPage';
import { ReportingPage } from './pages/ReportingPage';
import { StandardRatesPage } from './pages/StandardRatesPage';
import { AllRatesPage } from './pages/AllRatesPage';
import { ActivitiesPage } from './pages/ActivitiesPage';

type PageType = 'dashboard' | 'users' | 'allocation' | 'attendance' | 'rates' | 'swaps' | 'reports' | 'standard-rates' | 'all-rates' | 'activities';

const AppContent: React.FC = () => {
  const [activePage, setActivePage] = useState<PageType>('dashboard');
  const { isAuthenticated, isLoading } = useAuth();

  const renderPage = () => {
    switch (activePage) {
      case 'dashboard':
        return <DashboardPage />;
      case 'users':
        return <UsersPage />;
      case 'allocation':
        return <WorkAllocationPage />;
      case 'attendance':
        return <AttendancePage />;
      case 'rates':
        return <RatesPage />;
      case 'swaps':
        return <EmployeeSwapPage />;
      case 'reports':
        return <ReportingPage />;
      case 'standard-rates':
        return <StandardRatesPage />;
      case 'all-rates':
        return <AllRatesPage />;
      case 'activities':
        return <ActivitiesPage />;
      default:
        return <DashboardPage />;
    }
  };

  // Show loading state
  if (isLoading) {
    return (
      <div className="flex h-screen items-center justify-center bg-gray-100">
        <div className="text-center">
          <div className="inline-block animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mb-4"></div>
          <p className="text-gray-600">Loading...</p>
        </div>
      </div>
    );
  }

  // Show login page if not authenticated
  if (!isAuthenticated) {
    return <LoginPage />;
  }

  // Show main app if authenticated
  return (
    <div className="flex h-screen bg-gray-100">
      <Sidebar activePage={activePage} onNavigate={(page) => setActivePage(page as PageType)} />
      
      <div className="flex-1 flex flex-col overflow-hidden">
        <Header />
        
        <main className="flex-1 overflow-y-auto">
          {renderPage()}
        </main>
      </div>
    </div>
  );
};

function App() {
  return (
    <AuthProvider>
      <AppContent />
    </AuthProvider>
  );
}

export default App;