import AppRouter from "AppRouter";
import { BrowserRouter } from "react-router-dom";
import { useMsal } from "@azure/msal-react";
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";
import { UNAUTHORIZED_TO_CONTINUE_ERROR_CODES } from "components/auth/constants";
import { clearUserInfo } from "features/login";

const App = (): JSX.Element => {
  const dispatch = useDispatch();
  const { instance } = useMsal();
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [t, i18n] = useTranslation();
  useEffect(() => {
    const id = globalAxios.interceptors.response.use(
      (response: AxiosResponse) => response,
      (e: AxiosError<{ code?: string }>) => {
        if (
          e?.response?.status === 401 &&
          e?.response?.data?.code &&
          !UNAUTHORIZED_TO_CONTINUE_ERROR_CODES.includes(e.response.data.code)
        ) {
          dispatch(clearToken());
          dispatch(clearUserInfo());
          instance.logoutRedirect({
            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());
        }}
      />
      <BrowserRouter>
        <AppRouter />
      </BrowserRouter>
    </>
  );
};

export default App;
