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 Dashboard from './Dashboard';
import FetchRequests from './FetchRequests';
import FetchRequestDetail from './FetchRequestDetail';
import ReportSnapshots from './ReportSnapshots';
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: "/dashboard", component: Dashboard, headerTitle: "Dashboard" },
  { path: "/fetch-requests", component: FetchRequests, headerTitle: "Fetch Requests" },
  { path: "/fetch-requests/:id", component: FetchRequestDetail, headerTitle: "Fetch Request" },
  { path: "/reports", component: ReportSnapshots, headerTitle: "Reports" },
  { 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") ? (
                      <Component basePath="/admin" />
                    ) : (
                      <Component />
                    )
                  }
                />
              ))}
            </Routes>
          </Box>

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