import * as React from 'react';
import { createRoot } from 'react-dom/client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import {
  BrowserRouter,
  Routes,
  Route
} from "react-router-dom";
import {
  Box,
  CssBaseline,
  Toolbar
} from "@mui/material";
import Home from './Home';
import FetchRequests from './FetchRequest/FetchRequestCreate';
import FetchRequestDetail from './FetchRequest/FetchRequestDetail';
import { RequireAuth } from './RequireAuth';
import { AppProvider, Admin } from '../react-openapi';
import { Buffer } from 'buffer';
import process from 'process';
import { AuthProvider } from "../react-auth";
import Header from './Header';
import Footer from './Footer';
import AppTheme from './shared-theme/AppTheme';
import { specConfiguration } from './openapi-config';

const queryClient = new QueryClient();

window.Buffer = Buffer;
window.process = process;

const rootElement = document.getElementById('root');
const root = createRoot(rootElement);

const AUTH_BASE = import.meta.env.VITE_AUTH_BASE_URL;

const routerMapping = [
  { path: "/", component: Home, headerTitle: "Home" },
  { path: "/home", component: Home, headerTitle: "Home" },
  { path: "/fetch-requests", component: FetchRequests, headerTitle: "Fetch Requests" },
  { path: "/fetch-requests/:id", component: FetchRequestDetail, headerTitle: "Fetch Request" },
  { path: "/admin/*", component: Admin, headerTitle: "Admin" },
];

root.render(
  <QueryClientProvider client={queryClient}>
  <AppProvider specConfiguration={specConfiguration}>
    <BrowserRouter>
      <AuthProvider authBaseUrl={AUTH_BASE}>
        <AppTheme>
          <CssBaseline enableColorScheme />
          <Header routerMapping={routerMapping} />

          <Box sx={{ pb: 8 }}>
            <Toolbar />

            <Routes>
              {routerMapping.map(({ path, component: Component }) => (
                <Route
                  key={path}
                  path={path}
                  element={
                    path.startsWith("/admin") ? (
                      <RequireAuth><Component basePath="/admin" /></RequireAuth>
                    ) : (
                      <Component />
                    )
                  }
                />
              ))}
            </Routes>
          </Box>

          <Footer />
        </AppTheme>
      </AuthProvider>
    </BrowserRouter>
  </AppProvider>
  </QueryClientProvider>
);
