import React, { useCallback } from "react";
import { loadAccessToken } from "features/auth/utils";
import { decodeToken } from "common/decodeToken";
import { useDispatch } 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 LicenseSummary from "./licenseSummary";
import PartnerLicense from "./partnerLicense";

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

  const redirectToTopPage = useCallback(() => {
    dispatch(clearToken());
    instance.logout({
      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;
