import React, { useCallback, useState, useEffect } from "react";
import { useMsal } from "@azure/msal-react";
import Footer from "components/footer";
import Header from "components/header";
import styles from "styles/app.module.scss";
import { UpdateTokenTimer } from "components/auth/updateTokenTimer";
import { clearToken } from "features/auth";
import { useDispatch, useSelector } from "react-redux";
import { AppDispatch } from "app/store";
import { getTranslationID } from "translation";
import { useTranslation } from "react-i18next";
import { CardLicenseIssuePopup } from "./cardLicenseIssuePopup";
import postAdd from "../../assets/images/post_add.svg";
import history from "../../assets/images/history.svg";
import { isApproveTier } from "../../features/auth/utils";
import { TIERS } from "../../components/auth/constants";
import {
  getMyAccountAsync,
  getPartnerLicenseAsync,
  ACCOUNTS_VIEW_LIMIT,
  selectTotal,
  selectOwnPartnerLicense,
  selectChildrenPartnerLicenses,
  selectAccountInfo,
} from "../../features/license/partnerLicense";
import { LicenseOrderPopup } from "./licenseOrderPopup";

const PartnerLicense: React.FC = (): JSX.Element => {
  const { instance } = useMsal();
  const dispatch: AppDispatch = useDispatch();
  const [t] = useTranslation();

  // popup制御関係
  const [isCardLicenseIssuePopupOpen, setIsCardLicenseIssuePopupOpen] =
    useState(false);
  const [islicenseOrderPopupOpen, setIslicenseOrderPopupOpen] = useState(false);

  // 階層表示用
  const tierNames: { [key: number]: string } = {
    // eslint-disable-next-line @typescript-eslint/naming-convention
    1: t(getTranslationID("common.label.tier1")),
    // eslint-disable-next-line @typescript-eslint/naming-convention
    2: t(getTranslationID("common.label.tier2")),
    // eslint-disable-next-line @typescript-eslint/naming-convention
    3: t(getTranslationID("common.label.tier3")),
    // eslint-disable-next-line @typescript-eslint/naming-convention
    4: t(getTranslationID("common.label.tier4")),
    // eslint-disable-next-line @typescript-eslint/naming-convention
    5: t(getTranslationID("common.label.tier5")),
  };

  const onlicenseIssueOpen = useCallback(() => {
    setIsCardLicenseIssuePopupOpen(true);
  }, [setIsCardLicenseIssuePopupOpen]);

  const onlicenseOrderOpen = useCallback(() => {
    setIslicenseOrderPopupOpen(true);
  }, [setIslicenseOrderPopupOpen]);

  // apiからの値取得関係
  const myAccountInfo = useSelector(selectAccountInfo);
  const total = useSelector(selectTotal);
  const ownPartnerLicenseInfo = useSelector(selectOwnPartnerLicense);
  const childrenPartnerLicensesInfo = useSelector(
    selectChildrenPartnerLicenses
  );

  // ログイン時に階層をチェック
  const isTier1 = isApproveTier([TIERS.TIER1]);
  const isTier2ToTier4 = isApproveTier([TIERS.TIER2, TIERS.TIER3, TIERS.TIER4]);

  // パラメーターを入れておく空配列
  // eslint-disable-next-line react-hooks/exhaustive-deps
  const hierarchicalElements: HierarchicalElements[] = [];

  // マウント時のみ実行
  useEffect(() => {
    dispatch(getMyAccountAsync());
    dispatch(
      getPartnerLicenseAsync({
        limit: ACCOUNTS_VIEW_LIMIT,
        offset: 0,
        accountId: myAccountInfo.accountId,
      })
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // 画面遷移時に実行
  // TODO 仮実装なので挙動は未検証
  useEffect(() => {
    if (hierarchicalElements.length === 1) {
      dispatch(getMyAccountAsync());
    }
    dispatch(
      getPartnerLicenseAsync({
        limit: ACCOUNTS_VIEW_LIMIT,
        offset: 0,
        accountId: myAccountInfo.accountId,
      })
    );
  }, [dispatch, hierarchicalElements, myAccountInfo]);

  return (
    <>
      {/* 表示確認用の仮画面 */}
      {/* isPopupOpenがfalseの場合はポップアップのhtmlを生成しないように対応。これによりポップアップは都度生成されて初期化の考慮が減る */}
      {isCardLicenseIssuePopupOpen && (
        <CardLicenseIssuePopup
          onClose={() => {
            setIsCardLicenseIssuePopupOpen(false);
          }}
        />
      )}
      {islicenseOrderPopupOpen && (
        <LicenseOrderPopup
          onClose={() => {
            setIslicenseOrderPopupOpen(false);
          }}
        />
      )}

      <div className={styles.wrap}>
        <Header userName="XXXXXX" />
        <UpdateTokenTimer />
        <main className={styles.main}>
          <div className="">
            <div className={styles.pageHeader}>
              <h1 className={styles.pageTitle}>
                {t(getTranslationID("partnerLicense.label.title"))}
              </h1>
            </div>
          </div>

          <section className={styles.license}>
            <div>
              <h2>{t(getTranslationID("partnerLicense.label.subTitle"))}</h2>
              <ul className={styles.menuAction}>
                <li>
                  <a
                    href="license_partner.html"
                    className={`${styles.menuLink} ${styles.isActive}`}
                  >
                    <img
                      src="images/undo.svg"
                      alt=""
                      className={styles.menuIcon}
                    />
                    {t(getTranslationID("partnerLicense.label.returnButton"))}
                  </a>
                </li>
                <li>
                  {isTier2ToTier4 && (
                    // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
                    <a
                      className={`${styles.menuLink} ${styles.isActive}`}
                      onClick={onlicenseOrderOpen}
                    >
                      <img src={postAdd} alt="" className={styles.menuIcon} />
                      {t(
                        getTranslationID(
                          "partnerLicense.label.orderLicenseButton"
                        )
                      )}
                    </a>
                  )}
                </li>
                <li>
                  {isTier2ToTier4 && (
                    <a
                      href="license_history.html"
                      className={`${styles.menuLink} ${styles.isActive}`}
                    >
                      <img src={history} alt="" className={styles.menuIcon} />
                      {t(
                        getTranslationID(
                          "partnerLicense.label.orderHistoryButton"
                        )
                      )}
                    </a>
                  )}
                </li>
                {/* 第1階層 */}
                <li>
                  {isTier1 && (
                    // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
                    <a
                      className={`${styles.menuLink} ${styles.isActive}`}
                      onClick={onlicenseIssueOpen}
                    >
                      <img src={postAdd} alt="" className={styles.menuIcon} />
                      {t(
                        getTranslationID(
                          "partnerLicense.label.IssueLicenseCardButton"
                        )
                      )}
                    </a>
                  )}
                </li>
                <li>
                  <a
                    href="license_partner_card_history.html"
                    className={`${styles.menuLink} ${styles.isActive}`}
                  >
                    <img src={history} alt="" className={styles.menuIcon} />
                    {t(
                      getTranslationID(
                        "partnerLicense.label.displayCardHistoryButton"
                      )
                    )}
                  </a>
                </li>
              </ul>
              {/* TODO パンくずリストの表示内容、リンク先は仮 */}
              <ul className={styles.brCrumbLicense}>
                <li>
                  <a href="">OMDS US</a>
                </li>
                <li>
                  <a href="">BBBB inc.</a>
                </li>
                <li>ABCDEFGHIJKLM corp.</li>
              </ul>
              <table className={`${styles.table} ${styles.partner}`}>
                <tr className={styles.tableHeader}>
                  <th>{t(getTranslationID("partnerLicense.label.name"))}</th>
                  <th>
                    {t(getTranslationID("partnerLicense.label.category"))}
                  </th>
                  <th>
                    {t(getTranslationID("partnerLicense.label.accountId"))}
                  </th>
                  <th>
                    {t(getTranslationID("partnerLicense.label.stockLicense"))}
                  </th>
                  <th>
                    {t(getTranslationID("partnerLicense.label.issueRequested"))}
                  </th>
                  <th>
                    {t(getTranslationID("partnerLicense.label.shortage"))}
                  </th>
                  <th className={styles.noLine}>
                    {t(
                      getTranslationID("partnerLicense.label.issueRequesting")
                    )}
                  </th>
                  {/* eslint-disable-next-line jsx-a11y/control-has-associated-label */}
                  <th />
                </tr>
                <tr className={styles.isOpen}>
                  <td>{ownPartnerLicenseInfo.companyName}</td>
                  <td>{tierNames[ownPartnerLicenseInfo.tier]}</td>
                  <td>{ownPartnerLicenseInfo.accountId}</td>
                  <td>{ownPartnerLicenseInfo.stockLicense}</td>
                  <td>{ownPartnerLicenseInfo.issuedRequested}</td>
                  <td>{ownPartnerLicenseInfo.shortage}</td>
                  <td>{ownPartnerLicenseInfo.issueRequesting}</td>
                  <td>
                    <ul
                      className={`${styles.menuAction} ${styles.menuInTable}`}
                    >
                      <li>
                        {/* TODO リンク先は仮 ボタン表示制御未実装 */}
                        <a
                          href="license_partner_history.html"
                          className={styles.menuLink}
                        >
                          {t(
                            getTranslationID(
                              "partnerLicense.label.orderHistoryButton"
                            )
                          )}
                        </a>
                      </li>
                    </ul>
                  </td>
                </tr>
                {childrenPartnerLicensesInfo.map((value) => (
                  <tr key={value.accountId}>
                    <td title="">{value.companyName}</td>
                    <td>{tierNames[value.tier]}</td>
                    <td>{value.accountId}</td>
                    <td>{value.stockLicense}</td>
                    <td>{value.issuedRequested}</td>
                    <td>{value.shortage}</td>
                    <td>{value.issueRequesting}</td>
                    <td>
                      <ul className={`${styles.menuAction} ${styles.inTable}`}>
                        <li>
                          {/* TODO リンク先は仮 ボタン表示制御未実装 */}
                          <a
                            href="license_partner_5.html"
                            className={`${styles.menuLink} ${styles.isActive}`}
                          >
                            {t(
                              getTranslationID(
                                "partnerLicense.label.viewDetails"
                              )
                            )}
                          </a>
                        </li>
                      </ul>
                    </td>
                  </tr>
                ))}
              </table>
              {/* pagenation */}
              <div className={styles.pagenation}>
                <nav className={styles.pagenationNav}>
                  <span className={styles.pagenationTotal}>
                    {total}{" "}
                    {t(getTranslationID("partnerLicense.label.accounts"))}
                  </span>
                  {/* TODO ページ数は仮、ページ遷移、ボタン表示制御未実装 */}
                  <a href="">«</a>
                  <a href="">‹</a>1 of 2
                  <a href="" className={` ${styles.isActive}`}>
                    ›
                  </a>
                  <a href="" className={` ${styles.isActive}`}>
                    »
                  </a>
                </nav>
              </div>
            </div>
          </section>
        </main>
        <div>
          <button
            type="button"
            className={styles.buttonText}
            onClick={() => {
              instance.logout({ postLogoutRedirectUri: "/" });
              dispatch(clearToken());
            }}
          >
            sign out
          </button>
        </div>{" "}
        <Footer />
      </div>
    </>
  );
};

export interface HierarchicalElements {
  accountId: string;
  companyName: string;
}
export default PartnerLicense;
