import { FunctionComponent } from "preact";
import { ErrorBoundary, lazy, LocationProvider, Route, Router, useLocation } from "preact-iso";
import { ru } from "primelocale/js/ru.js";
import { addLocale, locale, PrimeReactProvider } from "primereact/api";
import { useMountEffect } from "primereact/hooks";
import Page404 from "./pages/404";
import LoginPage from "./pages/login";
import { AppProvider, useAppContext } from "./providers/AuthProvider";

const HomePage: FunctionComponent = () => {
  const { route } = useLocation();
  const { isLoggedIn } = useAppContext();
  if (isLoggedIn.value) route("/profile/tasks", true);
  else route("/login", true);
  return <div>Redirecting...</div>;
};

export function App() {
  useMountEffect(() => {
    addLocale("ru", ru);
    locale("ru");
  });
  return (
    <AppProvider>
      <PrimeReactProvider
        value={{
          unstyled: true,
        }}
      >
        <LocationProvider>
          <ErrorBoundary>
            <Router>
              <Route path="/" component={HomePage} />
              <Route path="/login" component={LoginPage} />
              <Route path="/profile/*" component={lazy(() => import("./pages/profile"))} />
              <Route default component={() => <Page404 />} />
            </Router>
          </ErrorBoundary>
        </LocationProvider>
      </PrimeReactProvider>
    </AppProvider>
  );
}
