import React from "react";
import "./App.css";
import {
  Route,
  RouterProvider,
  createBrowserRouter,
  createRoutesFromElements,
} from "react-router-dom";
import { NotFoundRoute } from "./routes/NotFound";
import { OIDCCbRoute } from "./routes/auth/OIDCCbRoute";
import { BaseLoginPage } from "./widgets/BaseLoginPage";
import { BaseAuthenticatedPage } from "./widgets/BaseAuthenticatedPage";
import { LoginRoute } from "./routes/auth/LoginRoute";
import { AuthApi } from "./api/AuthApi";
import { IsoFilesRoute } from "./routes/IsoFilesRoute";
import { ServerApi } from "./api/ServerApi";
import { SysInfoRoute } from "./routes/SysInfoRoute";
import { VirtualMachinesRoute } from "./routes/VirtualMachinesRoute";
import { CreateVMRoute, EditVMRoute } from "./routes/EditVMRoute";

interface AuthContext {
  signedIn: boolean;
  setSignedIn: (signedIn: boolean) => void;
}

const AuthContextK = React.createContext<AuthContext | null>(null);

export function App() {
  const [signedIn, setSignedIn] = React.useState(AuthApi.SignedIn);

  const context: AuthContext = {
    signedIn: signedIn,
    setSignedIn: (s) => setSignedIn(s),
  };

  const router = createBrowserRouter(
    createRoutesFromElements(
      signedIn || ServerApi.Config.auth_disabled ? (
        <Route path="*" element={<BaseAuthenticatedPage />}>
          <Route path="iso" element={<IsoFilesRoute />} />

          <Route path="vms" element={<VirtualMachinesRoute />} />
          <Route path="vms/new" element={<CreateVMRoute />} />
          <Route path="vm/:uuid/edit" element={<EditVMRoute />} />

          <Route path="sysinfo" element={<SysInfoRoute />} />
          <Route path="*" element={<NotFoundRoute />} />
        </Route>
      ) : (
        <Route path="*" element={<BaseLoginPage />}>
          <Route path="" element={<LoginRoute />} />
          <Route path="oidc_cb" element={<OIDCCbRoute />} />
          <Route path="*" element={<NotFoundRoute />} />
        </Route>
      )
    )
  );

  return (
    <AuthContextK.Provider value={context}>
      <RouterProvider router={router} />
    </AuthContextK.Provider>
  );
}

export function useAuth(): AuthContext {
  return React.useContext(AuthContextK)!;
}
