import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { AuthProvider, useAuth } from './contexts/AuthContext';
import { ToastProvider } from './components/Toast';
import Layout from './components/Layout';
import Login from './pages/Login';
import Dashboard from './pages/Dashboard';
import Properties from './pages/Properties';
import PropertyGroups from './pages/PropertyGroups';
import Tenants from './pages/Tenants';
import Contracts from './pages/Contracts';
import IncomeReceipts from './pages/IncomeReceipts';
import ExpenseTemplates from './pages/ExpenseTemplates';
import ExpenseReceipts from './pages/ExpenseReceipts';
import Incidents from './pages/Incidents';
import Maintenance from './pages/Maintenance';
import Documents from './pages/Documents';
import BankAccounts from './pages/BankAccounts';

function PrivateRoute({ children }: { children: React.ReactNode }) {
  const { isAuthenticated, loading } = useAuth();
  if (loading) return null;
  return isAuthenticated ? <>{children}</> : <Navigate to="/login" replace />;
}

function AppRoutes() {
  return (
    <Routes>
      <Route path="/login" element={<Login />} />
      <Route path="/" element={<PrivateRoute><Layout /></PrivateRoute>}>
        <Route index element={<Navigate to="/dashboard" replace />} />
        <Route path="dashboard" element={<Dashboard />} />
        <Route path="properties" element={<Properties />} />
        <Route path="property-groups" element={<PropertyGroups />} />
        <Route path="tenants" element={<Tenants />} />
        <Route path="contracts" element={<Contracts />} />
        <Route path="income-receipts" element={<IncomeReceipts />} />
        <Route path="expense-templates" element={<ExpenseTemplates />} />
        <Route path="expense-receipts" element={<ExpenseReceipts />} />
        <Route path="incidents" element={<Incidents />} />
        <Route path="maintenance" element={<Maintenance />} />
        <Route path="documents" element={<Documents />} />
        <Route path="bank-accounts" element={<BankAccounts />} />
      </Route>
    </Routes>
  );
}

export default function App() {
  return (
    <BrowserRouter>
      <AuthProvider>
        <ToastProvider>
          <AppRoutes />
        </ToastProvider>
      </AuthProvider>
    </BrowserRouter>
  );
}
