/* eslint-disable jsx-a11y/label-has-associated-control */
import { useTranslation } from "react-i18next";
import { getTranslationID } from "translation";
import Header from "components/header";
import { AppDispatch } from "app/store";
import { useDispatch, useSelector } from "react-redux";
import styles from "styles/app.module.scss";
import { TIERS } from "components/auth/constants";
import Footer from "components/footer";
import { useCallback, useEffect, useState } from "react";
import {
  getAccountInfoMinimalAccessAsync,
  getTermsInfoAsync,
  updateAcceptedVersionAsync,
  selectTier,
  selectIsLoading,
  selectTermVersions,
} from "features//terms";
import { selectLocalStorageKeyforIdToken } from "features/login";
import { useNavigate } from "react-router-dom";
import {
  clearToken,
  isAdminUser,
  isApproveTier,
  isStandardUser,
  loadAccessToken,
} from "features/auth";
import { useMsal } from "@azure/msal-react";

const TermsPage: React.FC = (): JSX.Element => {
  const [t] = useTranslation();
  const dispatch: AppDispatch = useDispatch();
  const { instance } = useMsal();
  const navigate = useNavigate();
  const updateAccceptVersions = useSelector(selectTermVersions);
  const localStorageKeyforIdToken = useSelector(
    selectLocalStorageKeyforIdToken
  );
  const tier = useSelector(selectTier);
  const isLoading = useSelector(selectIsLoading);
  const [isCheckedEula, setIsCheckedEula] = useState(false);
  const [isCheckedPrivacyNotice, setIsCheckedPrivacyNotice] = useState(false);
  const [isCheckedDpa, setIsCheckedDpa] = useState(false);

  const [isClickedEulaLink, setIsClickedEulaLink] = useState(false);
  const [isClickedPrivacyNoticeLink, setIsClickedPrivacyNoticeLink] =
    useState(false);
  const [isClickedDpaLink, setIsClickedDpaLink] = useState(false);

  // 画面起動時
  useEffect(() => {
    // ログイン済みの場合、ログイン後の遷移先を決定する
    if (loadAccessToken()) {
      // 第一～第四階層の管理者はライセンス画面へ遷移
      if (
        isApproveTier([TIERS.TIER1, TIERS.TIER2, TIERS.TIER3, TIERS.TIER4]) &&
        isAdminUser()
      ) {
        navigate("/license");
        return;
      }
      // 第五階層の管理者はユーザー画面へ遷移
      if (isApproveTier([TIERS.TIER5]) && isAdminUser()) {
        navigate("/user");
        return;
      }
      // 一般ユーザーはdictationPageへ遷移
      if (isStandardUser()) {
        navigate("/dictations");
        return;
      }
      // それ以外は認証エラー画面へ遷移
      instance.logoutRedirect({
        postLogoutRedirectUri: "/AuthError",
      });
      clearToken();
      return;
    }

    dispatch(getTermsInfoAsync());
    if (localStorageKeyforIdToken) {
      dispatch(getAccountInfoMinimalAccessAsync({ localStorageKeyforIdToken }));
    } else {
      // ログイン画面を経由していないため、トップページに遷移する
      navigate("/");
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // ユーザーが第5階層であるかどうかを判定する(アクセストークンから自分の階層を取得できないので自前で作成)
  const isTier5 = () => TIERS.TIER5.includes(tier.toString());

  // ボタン押下可否判定ロジック
  const canClickButton = () => {
    if (isTier5()) {
      return isCheckedEula && isCheckedPrivacyNotice;
    }
    return isCheckedEula && isCheckedPrivacyNotice && isCheckedDpa;
  };

  // ボタン押下時処理
  const onAcceptTermsOfUse = useCallback(async () => {
    if (
      localStorageKeyforIdToken &&
      updateAccceptVersions.acceptedVerDPA !== "" &&
      updateAccceptVersions.acceptedVerEULA !== "" &&
      updateAccceptVersions.acceptedVerPrivacyNotice !== ""
    ) {
      const { meta } = await dispatch(
        updateAcceptedVersionAsync({
          tier,
          localStorageKeyforIdToken,
          updateAccceptVersions,
        })
      );

      // 同意済バージョンが更新できたら、再度トークン生成を行う
      if (meta.requestStatus === "fulfilled") {
        navigate("/login");
      }
    }
  }, [
    navigate,
    localStorageKeyforIdToken,
    updateAccceptVersions,
    tier,
    dispatch,
  ]);
  if (isLoading) {
    return (
      <>
        <Header />
        <h3>loading ...</h3>
        <Footer />
      </>
    );
  }
  return (
    <div className={styles.wrap}>
      <Header />

      <main className={styles.main}>
        <div className={styles.mainSmall}>
          <div>
            <h1 className={`${styles.marginBtm1} ${styles.alignCenter}`}>
              {t(getTranslationID("termsPage.label.title"))}
            </h1>
          </div>
          <section className={styles.form}>
            <form action="" name="" method="">
              <dl className={`${styles.formList} ${styles.hasbg}`}>
                <dt className={styles.formTitle} />

                <dd className={`${styles.full} ${styles.alignCenter}`}>
                  <p>
                    {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */}
                    <a
                      href="/" /* TODO Eula用の利用規約リンクが決定したら設定を行う */
                      target="_blank"
                      className={styles.linkTx}
                      onClick={() => setIsClickedEulaLink(true)}
                      data-tag="open-eula"
                    >
                      {t(getTranslationID("termsPage.label.linkOfEula"))}
                    </a>
                    {` ${t(getTranslationID("termsPage.label.forOdms"))}`}
                  </p>
                  <p>
                    <label htmlFor="checkboxEula">
                      <input
                        id="checkboxEula"
                        type="checkbox"
                        checked={isCheckedEula}
                        className={styles.formCheck}
                        value=""
                        onChange={(e) => setIsCheckedEula(e.target.checked)}
                        disabled={!isClickedEulaLink}
                        data-tag="accept-eula"
                      />
                      {t(
                        getTranslationID("termsPage.label.checkBoxForConsent")
                      )}
                    </label>
                  </p>
                </dd>
                <dd className={`${styles.full} ${styles.alignCenter}`}>
                  <p>
                    {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */}
                    <a
                      href="/" /* TODO PrivacyNotice用の利用規約リンクが決定したら設定を行う */
                      target="_blank"
                      className={styles.linkTx}
                      onClick={() => setIsClickedPrivacyNoticeLink(true)}
                      data-tag="open-pricacy-notice"
                    >
                      {t(
                        getTranslationID("termsPage.label.linkOfPrivacyNotice")
                      )}
                    </a>
                    {` ${t(getTranslationID("termsPage.label.forOdms"))}`}
                  </p>
                  <p>
                    <label htmlFor="checkboxPrivacyNotice">
                      <input
                        id="checkboxPrivacyNotice"
                        type="checkbox"
                        checked={isCheckedPrivacyNotice}
                        className={styles.formCheck}
                        value=""
                        onChange={(e) =>
                          setIsCheckedPrivacyNotice(e.target.checked)
                        }
                        disabled={!isClickedPrivacyNoticeLink}
                        data-tag="accept-privacy-notice"
                      />
                      {t(
                        getTranslationID("termsPage.label.checkBoxForConsent")
                      )}
                    </label>
                  </p>
                </dd>
                {/* 第五階層以外の場合はDPAのリンクをあわせて表示する */}
                {!isTier5() && (
                  <dd className={`${styles.full} ${styles.alignCenter}`}>
                    <p>
                      {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */}
                      <a
                        href="/" /* TODO Dpa用の利用規約リンクが決定したら設定を行う */
                        target="_blank"
                        className={styles.linkTx}
                        onClick={() => setIsClickedDpaLink(true)}
                        data-tag="open-dpa"
                      >
                        {t(getTranslationID("termsPage.label.linkOfDpa"))}
                      </a>
                      {` ${t(getTranslationID("termsPage.label.forOdms"))}`}
                    </p>
                    <p>
                      <label htmlFor="checkboxDpa">
                        <input
                          id="checkboxDpa"
                          type="checkbox"
                          checked={isCheckedDpa}
                          className={styles.formCheck}
                          value=""
                          onChange={(e) => setIsCheckedDpa(e.target.checked)}
                          disabled={!isClickedDpaLink}
                          data-tag="accept-dpa"
                        />
                        {t(
                          getTranslationID("termsPage.label.checkBoxForConsent")
                        )}
                      </label>
                    </p>
                  </dd>
                )}
                <dd className={`${styles.full} ${styles.alignCenter}`}>
                  <p>
                    <input
                      type="button"
                      name="submit"
                      value={t(getTranslationID("termsPage.label.button"))}
                      className={`${styles.formSubmit} ${styles.marginBtm1} ${
                        canClickButton() ? styles.isActive : ""
                      }`}
                      onClick={onAcceptTermsOfUse}
                      data-tag="accept-terms"
                    />
                  </p>
                </dd>
              </dl>
            </form>
          </section>
        </div>
      </main>
      <Footer />
    </div>
  );
};

export default TermsPage;
