import type { ReactNode } from "react";
import { Navigate, Route, Routes } from "react-router-dom";

import { AuthProvider, useAuth } from "./auth/AuthContext";
import { AdminPage } from "./pages/AdminPage";
import { KontrollPage } from "./pages/KontrollPage";
import { LoginPage } from "./pages/LoginPage";
import { ObjektListPage } from "./pages/ObjektListPage";

function GeschuetzteRoute({ children }: { children: ReactNode }) {
  const { eingeloggt } = useAuth();
  if (!eingeloggt) {
    return <Navigate to="/login" replace />;
  }
  return <>{children}</>;
}

function AdminRoute({ children }: { children: ReactNode }) {
  const { eingeloggt, istAdmin } = useAuth();
  if (!eingeloggt) {
    return <Navigate to="/login" replace />;
  }
  if (!istAdmin) {
    return <Navigate to="/objekte" replace />;
  }
  return <>{children}</>;
}

export default function App() {
  return (
    <AuthProvider>
      <Routes>
        <Route path="/login" element={<LoginPage />} />
        <Route
          path="/objekte"
          element={
            <GeschuetzteRoute>
              <ObjektListPage />
            </GeschuetzteRoute>
          }
        />
        <Route
          path="/objekte/:objektId/kontrolle"
          element={
            <GeschuetzteRoute>
              <KontrollPage />
            </GeschuetzteRoute>
          }
        />
        <Route
          path="/admin"
          element={
            <AdminRoute>
              <AdminPage />
            </AdminRoute>
          }
        />
        <Route path="*" element={<Navigate to="/objekte" replace />} />
      </Routes>
    </AuthProvider>
  );
}
