import React from "react";
import {
  createBrowserRouter,
  createRoutesFromElements,
  Route,
  RouterProvider,
} from "react-router";
import { AuthApi } from "./api/AuthApi";
import { ServerApi } from "./api/ServerApi";
import { LoginRoute } from "./routes/auth/LoginRoute";
import { OIDCCbRoute } from "./routes/auth/OIDCCbRoute";
import { HomeRoute } from "./routes/HomeRoute";
import { NotFoundRoute } from "./routes/NotFoundRoute";
import { BaseLoginPage } from "./widgets/auth/BaseLoginPage";
import BaseAuthenticatedPage from "./widgets/dashboard/BaseAuthenticatedPage";

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

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

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

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

  const router = createBrowserRouter(
    createRoutesFromElements(
      signedIn || ServerApi.Config.auth_disabled ? (
        <Route path="*" element={<BaseAuthenticatedPage />}>
          <Route path="" element={<HomeRoute />} />
          <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 value={context}>
      <RouterProvider router={router} />
    </AuthContextK>
  );
}

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