/* eslint-disable jsx-a11y/control-has-associated-label */
import { AppDispatch } from "app/store";
import { UpdateTokenTimer } from "components/auth/updateTokenTimer";
import Footer from "components/footer";
import Header from "components/header";
import React, { useCallback, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import styles from "styles/app.module.scss";
import { isApproveTier } from "features/auth";
import {
  LIMIT_PARTNER_VIEW_NUM,
  selectCurrentPage,
  selectIsLoading,
  selectOffset,
  selectTotal,
  selectTotalPage,
  getPartnerInfoAsync,
  selectPartnersInfo,
} from "features/partner/index";
import {
  changeDelegateAccount,
  savePageInfo,
} from "features/partner/partnerSlice";
import { getTranslationID } from "translation";
import { useTranslation } from "react-i18next";
import { getDelegationTokenAsync } from "features/auth/operations";
import { useNavigate } from "react-router-dom";
import personAdd from "../../assets/images/person_add.svg";
import { TIERS } from "../../components/auth/constants";
import { AddPartnerAccountPopup } from "./addPartnerAccountPopup";
import checkFill from "../../assets/images/check_fill.svg";

const PartnerPage: React.FC = (): JSX.Element => {
  const dispatch: AppDispatch = useDispatch();
  const [isPopupOpen, setIsPopupOpen] = useState(false);
  const [t] = useTranslation();
  const navigate = useNavigate();
  const total = useSelector(selectTotal);
  const totalPage = useSelector(selectTotalPage);
  const offset = useSelector(selectOffset);
  const currentPage = useSelector(selectCurrentPage);
  const isLoading = useSelector(selectIsLoading);

  // apiからの値取得関係
  const partnerInfo = useSelector(selectPartnersInfo);

  // 階層表示用
  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")),
  };

  // 第1～3階層にボタンを表示する
  const isVisibleButton = isApproveTier([
    TIERS.TIER1,
    TIERS.TIER2,
    TIERS.TIER3,
  ]);

  // 第4階層でdealerManagementを表示
  const isVisibleDealerManagement = isApproveTier([TIERS.TIER4]);

  const onOpen = useCallback(() => {
    setIsPopupOpen(true);
  }, [setIsPopupOpen]);

  // パートナー取得APIを呼び出す
  useEffect(() => {
    dispatch(
      getPartnerInfoAsync({
        limit: LIMIT_PARTNER_VIEW_NUM,
        offset,
      })
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dispatch, currentPage]);

  // ページネーションのボタンクリック時のアクション
  const movePage = (targetOffset: number) => {
    dispatch(
      savePageInfo({ limit: LIMIT_PARTNER_VIEW_NUM, offset: targetOffset })
    );
  };
  // 代理操作開始処理
  const startDealerManagement = useCallback(
    async (delegatedAccountId: number, delegatedCompanyName: string) => {
      if (
        /* eslint-disable-next-line no-alert */
        !window.confirm(t(getTranslationID("common.message.dialogConfirm")))
      ) {
        return;
      }
      dispatch(
        changeDelegateAccount({ delegatedAccountId, delegatedCompanyName })
      );
      const { meta } = await dispatch(getDelegationTokenAsync());
      if (meta.requestStatus === "fulfilled") {
        navigate("/user");
      }
    },
    [dispatch, navigate, t]
  );

  // HTML
  return (
    <>
      <AddPartnerAccountPopup
        isOpen={isPopupOpen}
        onClose={() => {
          setIsPopupOpen(false);
        }}
      />
      <div className={styles.wrap}>
        <Header />
        <UpdateTokenTimer />
        <main className={styles.main}>
          <div className={styles.pageHeader}>
            <h1 className={styles.pageTitle}>
              {t(getTranslationID("partnerPage.label.title"))}
            </h1>
          </div>
          <section className={styles.partners}>
            <div>
              <ul className={styles.menuAction}>
                <li>
                  {isVisibleButton && (
                    // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
                    <a
                      className={`${styles.menuLink} ${styles.isActive}`}
                      onClick={onOpen}
                    >
                      <img src={personAdd} alt="" className={styles.menuIcon} />
                      {t(getTranslationID("partnerPage.label.addAccount"))}
                    </a>
                  )}
                </li>
              </ul>
              <table
                className={`${styles.table} ${styles.partner} ${
                  styles.marginBtm3
                } ${isVisibleDealerManagement ? styles.role4 : ""}`}
              >
                <tr className={styles.tableHeader}>
                  <th className={styles.clm0}>{/** th is empty */}</th>
                  <th>
                    <a>{t(getTranslationID("partnerPage.label.name"))}</a>
                  </th>
                  <th>
                    <a>{t(getTranslationID("partnerPage.label.category"))}</a>
                  </th>
                  <th>
                    <a>{t(getTranslationID("partnerPage.label.accountId"))}</a>
                  </th>
                  <th>
                    <a>{t(getTranslationID("partnerPage.label.country"))}</a>
                  </th>
                  <th>
                    <a>
                      {t(getTranslationID("partnerPage.label.primaryAdmin"))}
                    </a>
                  </th>
                  <th>
                    <a>{t(getTranslationID("partnerPage.label.email"))}</a>
                  </th>
                  <th>
                    <a>
                      {t(
                        getTranslationID("partnerPage.label.dealerManagement")
                      )}
                    </a>
                  </th>
                </tr>
                {!isLoading &&
                  partnerInfo.partners.length !== 0 &&
                  partnerInfo.partners.map((x) => (
                    // eslint-disable-next-line react/jsx-key
                    <tr>
                      <td className={styles.clm0}>
                        <ul className={styles.menuInTable}>
                          {isVisibleButton && (
                            <li>
                              <a>
                                {t(
                                  getTranslationID(
                                    "partnerPage.label.deleteAccount"
                                  )
                                )}
                              </a>
                            </li>
                          )}
                          {isVisibleDealerManagement && (
                            <li>
                              {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions */}
                              <a
                                onClick={() => {
                                  startDealerManagement(x.accountId, x.name);
                                }}
                                className={
                                  x.dealerManagement ? "" : styles.isDisable
                                }
                              >
                                {t(
                                  getTranslationID(
                                    "partnerPage.label.dealerManagement"
                                  )
                                )}
                              </a>
                            </li>
                          )}
                        </ul>
                      </td>
                      <td>{x.name}</td>
                      <td>{tierNames[x.tier]}</td>
                      <td>{x.accountId}</td>
                      <td>{x.country}</td>
                      <td>{x.primaryAdmin ?? "-"}</td>
                      <td>{x.email ?? "-"}</td>
                      <td>
                        <img
                          src={x.dealerManagement ? checkFill : ""}
                          alt=""
                          className={styles.menuIcon}
                        />
                      </td>
                    </tr>
                  ))}
              </table>
              {!isLoading && partnerInfo.partners.length === 0 && (
                <p
                  style={{
                    textAlign: "center",
                    width: "1420px",
                  }}
                >
                  {t(getTranslationID("common.message.listEmpty"))}
                </p>
              )}
              {/** pagenation */}
              <div className={styles.pagenation}>
                <nav className={styles.pagenationNav}>
                  <span className={styles.pagenationTotal}>
                    {`${total} ${t(
                      getTranslationID("partnerPage.label.partners")
                    )}`}
                  </span>
                  {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */}
                  <a
                    className={`${
                      !isLoading && currentPage !== 1 ? styles.isActive : ""
                    }`}
                    onClick={() => {
                      movePage(0);
                    }}
                  >
                    «
                  </a>
                  {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions */}
                  <a
                    className={`${
                      !isLoading && currentPage !== 1 ? styles.isActive : ""
                    }`}
                    onClick={() => {
                      movePage((currentPage - 2) * LIMIT_PARTNER_VIEW_NUM);
                    }}
                  >
                    ‹
                  </a>
                  {` ${total !== 0 ? currentPage : 0} of ${
                    total !== 0 ? totalPage : 0
                  } `}
                  {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions */}
                  <a
                    className={`${
                      !isLoading && currentPage < totalPage
                        ? styles.isActive
                        : ""
                    }`}
                    onClick={() => {
                      movePage(currentPage * LIMIT_PARTNER_VIEW_NUM);
                    }}
                  >
                    ›
                  </a>
                  {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions */}
                  <a
                    className={`${
                      !isLoading && currentPage < totalPage
                        ? styles.isActive
                        : ""
                    }`}
                    onClick={() => {
                      movePage((totalPage - 1) * LIMIT_PARTNER_VIEW_NUM);
                    }}
                  >
                    »
                  </a>
                </nav>
              </div>
            </div>
          </section>
        </main>

        <Footer />
      </div>
    </>
  );
};

export default PartnerPage;
