import React from "react";
import {
  Route,
  RouterProvider,
  createBrowserRouter,
  createRoutesFromElements,
} from "react-router-dom";
import { AuthApi } from "./api/AuthApi";
import { ServerApi } from "./api/ServerApi";
import { AccountRoute } from "./routes/AccountRoute";
import { AccountsRoute } from "./routes/AccountsRoute";
import { BackupRoute } from "./routes/BackupRoute";
import { HomeRoute } from "./routes/HomeRoute";
import { InboxRoute } from "./routes/InboxRoute";
import { NotFoundRoute } from "./routes/NotFound";
import { TokensRoute } from "./routes/TokensRoute";
import { LoginRoute } from "./routes/auth/LoginRoute";
import { OIDCCbRoute } from "./routes/auth/OIDCCbRoute";
import { BaseAuthenticatedPage } from "./widgets/BaseAuthenticatedPage";
import { BaseLoginPage } from "./widgets/BaseLoginPage";

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);
      location.reload();
    },
  };

  const router = createBrowserRouter(
    createRoutesFromElements(
      signedIn || ServerApi.Config.auth_disabled ? (
        <Route path="*" element={<BaseAuthenticatedPage />}>
          <Route path="" element={<HomeRoute />} />
          <Route path="tokens" element={<TokensRoute />} />
          <Route path="backup" element={<BackupRoute />} />
          <Route path="accounts" element={<AccountsRoute />} />
          <Route path="account/:accountId" element={<AccountRoute />} />
          <Route path="inbox" element={<InboxRoute />} />

          <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)!;
}
