import React, { useCallback } from "react";
import { decodeToken } from "common/decodeToken";
import { useDispatch, useSelector } from "react-redux";
import { AppDispatch } from "app/store";
import { clearToken } from "features/auth";
import { useMsal } from "@azure/msal-react";
import { Token } from "common/token";
import { clearUserInfo } from "features/login";
import { selectAccessToken } from "features/auth/selectors";
import { LicenseSummary } from "./licenseSummary";
import PartnerLicense from "./partnerLicense";

const LicensePage: React.FC = (): JSX.Element => {
  const jwt = useSelector(selectAccessToken);
  const dispatch: AppDispatch = useDispatch();
  const { instance } = useMsal();

  const redirectToTopPage = useCallback(() => {
    dispatch(clearToken());
    dispatch(clearUserInfo());
    instance.logoutRedirect({
      postLogoutRedirectUri: "/",
    });
  }, [dispatch, instance]);

  const token = decodeToken(jwt ?? "");
  // 不正なアクセストークンの場合はトップページに遷移する
  if (!token) {
    redirectToTopPage();
  }
  const { tier } = token as Token;

  if (tier === 5) {
    // 第五階層とそれ以外で表示画面を振り分ける
    return <LicenseSummary />;
  }
  return <PartnerLicense />;
};

export default LicensePage;
