import "./App.css";

import { AppShell, useMantineTheme } from "@mantine/core";

import Header from "Components/Layout/Header/Header";
import "@mantine/notifications/styles.css";
import "@mantine/core/styles.css";
import { Notifications } from "@mantine/notifications";
import { useLayoutStore } from "Stores/LayoutStore";
import {
  defaultAnimationDuration,
  headerHeight,
  sideMenuWidth,
} from "GlobalVars";
import Sidebar from "Components/Layout/Sidebar/Sidebar";
import { Outlet, useLocation } from "react-router";
import { Helmet } from "react-helmet";
import { useEffect } from "react";
import { useMediaQuery } from "@mantine/hooks";
import BreadCrumbs from "Routes/Breadcrumbs/Breadcrumbs";
import keycloak, { getProfile } from "Api/Keycloak/Keycloak";
import { AuthenticationStore } from "Stores/AuthenticationStore";
import type { KeycloakProfile } from "keycloak-js";
import { useNavigate } from "react-router";

function App() {
  const { is_navbar_open, set_navbar_open } = useLayoutStore();
  const { set_token, set_profile } = AuthenticationStore();
  const navigate = useNavigate();

  const theme = useMantineTheme();

  const location = useLocation();
  const isMobile = useMediaQuery(`(max-width: ${theme.breakpoints.sm}`);

  useEffect(() => {
    if (isMobile)
      setTimeout(() => {
        set_navbar_open(false);
      }, 100);
  }, [location]);

  useEffect(() => {
    const refreshToken = () => {
      keycloak
        .updateToken(60)
        .then((refreshed) => {
          if (refreshed) {
            set_token(keycloak.token);
          }
        })
        .catch(() => {
          keycloak.logout();
        });
    };

    setInterval(refreshToken, 30000);
  }, []);

  return (
    <>
      <Helmet>
        <title>QMolSim</title>
        <meta
          name="description"
          content="Compute ground state energy of molecules using a distributed system"
        />
      </Helmet>

      <Notifications />

      <AppShell
        header={{ height: headerHeight }}
        aside={{
          width: sideMenuWidth,
          breakpoint: "sm",
          collapsed: {
            desktop: !is_navbar_open,
            mobile: !is_navbar_open,
          },
        }}
        padding="md"
        transitionDuration={defaultAnimationDuration}
      >
        <AppShell.Header id="Header" zIndex={1000}>
          <Header />
        </AppShell.Header>

        <AppShell.Aside id="Navbar">
          <Sidebar />
        </AppShell.Aside>

        <AppShell.Main className="body">
          <>
            <BreadCrumbs />
            <Outlet />
          </>
        </AppShell.Main>
      </AppShell>
    </>
  );
}

export default App;
