import React, { lazy, Suspense } from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import { useAuth } from '@/context/AuthContext';
import AppLayout from '@/layouts/AppLayout';
import Login from '@/pages/Login';
import NotFound from '@/pages/NotFound';

const Dashboard = lazy(() => import('@/pages/Dashboard'));
const Expenses = lazy(() => import('@/pages/Expenses'));
const Budgets = lazy(() => import('@/pages/Budgets'));
const Reports = lazy(() => import('@/pages/Reports'));
const RecurringExpenses = lazy(() => import('@/pages/RecurringExpenses'));
const Settings = lazy(() => import('@/pages/Settings'));
const Categories = lazy(() => import('@/pages/Categories'));

function PageLoader() {
    return (
        <div className="min-h-screen flex items-center justify-center">
            <div className="w-8 h-8 border-4 border-teal-600 border-t-transparent rounded-full animate-spin" />
        </div>
    );
}

function ProtectedRoute({ children }: { children: React.ReactNode }) {
    const { user, loading } = useAuth();

    if (loading) {
        return <PageLoader />;
    }

    if (!user) {
        return <Navigate to="/login" replace />;
    }

    return <AppLayout>{children}</AppLayout>;
}

function SuspendedPage({ children }: { children: React.ReactNode }) {
    return <Suspense fallback={<PageLoader />}>{children}</Suspense>;
}

export default function App() {
    return (
        <Routes>
            <Route path="/login" element={<Login />} />
            <Route path="/dashboard" element={<ProtectedRoute><SuspendedPage><Dashboard /></SuspendedPage></ProtectedRoute>} />
            <Route path="/expenses" element={<ProtectedRoute><SuspendedPage><Expenses /></SuspendedPage></ProtectedRoute>} />
            <Route path="/budgets" element={<ProtectedRoute><SuspendedPage><Budgets /></SuspendedPage></ProtectedRoute>} />
            <Route path="/reports" element={<ProtectedRoute><SuspendedPage><Reports /></SuspendedPage></ProtectedRoute>} />
            <Route path="/recurring" element={<ProtectedRoute><SuspendedPage><RecurringExpenses /></SuspendedPage></ProtectedRoute>} />
            <Route path="/settings" element={<ProtectedRoute><SuspendedPage><Settings /></SuspendedPage></ProtectedRoute>} />
            <Route path="/categories" element={<ProtectedRoute><SuspendedPage><Categories /></SuspendedPage></ProtectedRoute>} />
            <Route path="*" element={<NotFound />} />
        </Routes>
    );
}
