import { Authenticated, Unauthenticated, AuthLoading } from "convex/react";
import { ConvexAuthProvider } from "@convex-dev/auth/react";
import { RouterProvider, createBrowserRouter, Navigate, Outlet } from "react-router-dom";
import { Toaster } from "sonner";
import { convex } from "./lib/convex";
import { FilterProvider } from "./context/FilterContext";
import { AppShell } from "./components/layout/AppShell";
import { LoginPage } from "./pages/LoginPage";
import { DashboardPage } from "./pages/DashboardPage";
import { TransactionsPage } from "./pages/TransactionsPage";
import { CategoriesPage } from "./pages/CategoriesPage";
import { LoansPage } from "./pages/LoansPage";
import { SavingsChatPage } from "./pages/SavingsChatPage";
import { ImportPage } from "./pages/ImportPage";
import { SettingsPage } from "./pages/SettingsPage";
import { Skeleton } from "./components/ui/skeleton";
import { SeedInitializer } from "./components/SeedInitializer";

function OutletWrapper() {
  return <Outlet />;
}

function ProtectedLayout() {
  return (
    <>
      <Authenticated>
        <SeedInitializer />
        <FilterProvider>
          <AppShell>
            <OutletWrapper />
          </AppShell>
        </FilterProvider>
      </Authenticated>
      <Unauthenticated>
        <Navigate to="/login" replace />
      </Unauthenticated>
      <AuthLoading>
        <div className="flex min-h-screen items-center justify-center p-8">
          <Skeleton className="h-12 w-64" />
        </div>
      </AuthLoading>
    </>
  );
}

const router = createBrowserRouter([
  { path: "/login", element: <LoginPage /> },
  {
    element: <ProtectedLayout />,
    children: [
      { path: "/", element: <DashboardPage /> },
      { path: "/transaktionen", element: <TransactionsPage /> },
      { path: "/talk", element: <SavingsChatPage /> },
      { path: "/kategorien", element: <CategoriesPage /> },
      { path: "/kredite", element: <LoansPage /> },
      { path: "/import", element: <ImportPage /> },
      { path: "/einstellungen", element: <SettingsPage /> },
    ],
  },
]);

export default function App() {
  return (
    <ConvexAuthProvider client={convex}>
      <RouterProvider router={router} />
      <Toaster richColors position="top-right" />
    </ConvexAuthProvider>
  );
}
