import AppRouter from "AppRouter";
import { BrowserRouter } from "react-router-dom";
import { PublicClientApplication } from "@azure/msal-browser";
import { MsalProvider, useMsal } from "@azure/msal-react";
import { msalConfig } from "common/msalConfig";
import { useEffect, useLayoutEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import globalAxios, { AxiosError, AxiosResponse } from "axios";
import { clearToken } from "features/auth";
import { useTranslation } from "react-i18next";
import Snackbar from "components/snackbar";
import { selectSnackber } from "features/ui/selectors";
import { closeSnackbar } from "features/ui/uiSlice";

const App = (): JSX.Element => {
  const dispatch = useDispatch();
  const { instance } = useMsal();
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [t, i18n] = useTranslation();
  const pca = new PublicClientApplication(msalConfig);
  useEffect(() => {
    const id = globalAxios.interceptors.response.use(
      (response: AxiosResponse) => response,
      (e: AxiosError) => {
        if (e?.response?.status === 401) {
          dispatch(clearToken());
          instance.logout({
            postLogoutRedirectUri: "/?logout=true",
          });
        }
        return Promise.reject(e);
      }
    );
    const cleanup = () => {
      globalAxios.interceptors.response.eject(id);
    };
    return cleanup;
  }, [dispatch, instance]);

  // Language読み取り
  useLayoutEffect(() => {
    const language = document.cookie
      .trim()
      .split(";")
      .map((x) => x.split("="))
      .find((x) => x.length === 2 && x[0] === "language");

    if (language) {
      i18n.changeLanguage(language[1]);
    }
  }, [i18n]);

  const snackbarInfo = useSelector(selectSnackber);

  return (
    <>
      <Snackbar
        isOpen={snackbarInfo.isOpen}
        level={snackbarInfo.level}
        message={t(snackbarInfo.message)}
        duration={snackbarInfo.duration}
        onClose={() => {
          dispatch(closeSnackbar());
        }}
      />
      <MsalProvider instance={pca}>
        <BrowserRouter>
          <AppRouter />
        </BrowserRouter>
      </MsalProvider>
    </>
  );
};

export default App;
