import { AppDispatch } from "app/store";
import React, { useCallback, useEffect, useState } from "react";
import Header from "components/header";
import Footer from "components/footer";
import styles from "styles/app.module.scss";
import { UpdateTokenTimer } from "components/auth/updateTokenTimer";
import { useDispatch, useSelector } from "react-redux";
import {
  listUsersAsync,
  selectUserViews,
  selectIsLoading,
} from "features/user";
import { useTranslation } from "react-i18next";
import { getTranslationID } from "translation";
import { isLicenseStatusType } from "features/user/types";
import { LICENSE_STATUS } from "features/user/constants";
import { isApproveTier } from "features/auth/utils";
import { TIERS } from "components/auth/constants";
import personAdd from "../../assets/images/person_add.svg";
import checkFill from "../../assets/images/check_fill.svg";
import checkOutline from "../../assets/images/check_outline.svg";
import progress_activit from "../../assets/images/progress_activit.svg";
import { UserAddPopup } from "./popup";

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

  const [isPopupOpen, setIsPopupOpen] = useState(false);

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

  useEffect(() => {
    // ユーザ一覧取得処理を呼び出す
    dispatch(listUsersAsync());
  }, [dispatch]);

  const users = useSelector(selectUserViews);
  const isLoading = useSelector(selectIsLoading);
  // ユーザーが第5階層であるかどうかを判定する
  const isTier5 = isApproveTier([TIERS.TIER5]);

  return (
    <>
      <UserAddPopup
        isOpen={isPopupOpen}
        onClose={() => {
          setIsPopupOpen(false);
          dispatch(listUsersAsync());
        }}
      />
      <div className={styles.wrap}>
        <Header userName="XXXXXX" />
        <UpdateTokenTimer />
        <main className={styles.main}>
          <div className="">
            <div className={styles.pageHeader}>
              <h1 className={styles.pageTitle}>
                {t(getTranslationID("userListPage.label.title"))}
              </h1>
              <p className="pageTxt" />
            </div>
            <section className={styles.user}>
              <div>
                <ul className={styles.menuAction}>
                  <li>
                    {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events,jsx-a11y/no-static-element-interactions */}
                    <a
                      className={`${styles.menuLink} ${
                        !isLoading ? styles.isActive : ""
                      }`}
                      onClick={onOpen}
                    >
                      <img src={personAdd} alt="" className={styles.menuIcon} />
                      {t(getTranslationID("userListPage.label.addUser"))}
                    </a>
                  </li>
                </ul>
                <table className={`${styles.table} ${styles.user}`}>
                  <tbody>
                    <tr className={styles.tableHeader}>
                      <th className={styles.clm0}>{/** th is empty */}</th>
                      <th>{t(getTranslationID("userListPage.label.name"))}</th>
                      <th>{t(getTranslationID("userListPage.label.role"))}</th>
                      <th>
                        {t(getTranslationID("userListPage.label.authorID"))}
                      </th>
                      <th>
                        {t(getTranslationID("userListPage.label.encryption"))}
                      </th>
                      <th>
                        {t(getTranslationID("userListPage.label.prompt"))}
                      </th>
                      <th>
                        {t(getTranslationID("userListPage.label.typistGroup"))}
                      </th>
                      <th>{t(getTranslationID("userListPage.label.email"))}</th>
                      <th>
                        {t(getTranslationID("userListPage.label.status"))}
                      </th>
                      <th>
                        {t(getTranslationID("userListPage.label.expiration"))}
                      </th>
                      <th>
                        {t(getTranslationID("userListPage.label.remaining"))}
                      </th>
                      <th>
                        {t(getTranslationID("userListPage.label.autoRenew"))}
                      </th>
                      <th>
                        {t(getTranslationID("userListPage.label.licenseAlert"))}
                      </th>
                      <th>
                        {t(getTranslationID("userListPage.label.notification"))}
                      </th>
                      <th>
                        {t(
                          getTranslationID("userListPage.label.emailVerified")
                        )}
                      </th>
                    </tr>
                    {!isLoading &&
                      users.map((user) => {
                        const { isAlertLicenseStatus, isAlertRemaining } =
                          isAlertElement(user.licenseStatus);
                        return (
                          <tr key={user.email}>
                            <td className={styles.clm0}>
                              <ul className={styles.menuInTable}>
                                <li>
                                  <a href="">
                                    {t(
                                      getTranslationID(
                                        "userListPage.label.editUser"
                                      )
                                    )}
                                  </a>
                                </li>
                                {isTier5 && (
                                  <>
                                    <li>
                                      <a href="">
                                        {t(
                                          getTranslationID(
                                            "userListPage.label.licenseAllocation"
                                          )
                                        )}
                                      </a>
                                    </li>
                                    <li>
                                      <a href="">
                                        {t(
                                          getTranslationID(
                                            "userListPage.label.licenseDeallocation"
                                          )
                                        )}
                                      </a>
                                    </li>
                                  </>
                                )}
                                <li>
                                  <a href="">
                                    {t(
                                      getTranslationID(
                                        "userListPage.label.deleteUser"
                                      )
                                    )}
                                  </a>
                                </li>
                              </ul>
                            </td>
                            <td> {user.name}</td>
                            <td>{user.role}</td>
                            <td>{user.authorId}</td>
                            <td>{boolToElement(user.encryption)}</td>
                            <td>{boolToElement(user.prompt)}</td>
                            <td>{arrayToElement(user.typistGroupName)}</td>
                            <td>{user.email}</td>
                            <td>
                              <span
                                className={
                                  isAlertLicenseStatus ? styles.isAlert : ""
                                }
                              >
                                {user.licenseStatus}
                              </span>
                            </td>
                            <td>
                              <span
                                className={
                                  isAlertRemaining ? styles.isAlert : ""
                                }
                              >
                                {user.expiration}
                              </span>
                            </td>
                            <td>
                              <span
                                className={
                                  isAlertRemaining ? styles.isAlert : ""
                                }
                              >
                                {user.remaining}
                              </span>
                            </td>
                            <td>{boolToElement(user.autoRenew)}</td>
                            <td>{boolToElement(user.licenseAlert)}</td>
                            <td>{boolToElement(user.notification)}</td>
                            <td>{boolToElement(user.emailVerified)}</td>
                          </tr>
                        );
                      })}
                  </tbody>
                </table>
                {isLoading && (
                  <img
                    src={progress_activit}
                    className={styles.icLoading}
                    alt="Loading"
                  />
                )}
              </div>
            </section>
          </div>
        </main>
        <Footer />
      </div>
    </>
  );
};

// boolかstringを受け取って、stringの場合はそのまま返し、boolの場合はチェックマークON/OFFを返す
const boolToElement = (value: boolean | string): JSX.Element | string => {
  if (typeof value === "string") {
    return value;
  }
  return value ? (
    <img src={checkFill} alt="" className={styles.menuIcon} />
  ) : (
    <img src={checkOutline} alt="" className={styles.menuIcon} />
  );
};

// 文字列の配列または文字列を受け取って、文字列の場合はそのまま返し、配列の場合は最後の要素以外に<br>をつけて返す
const arrayToElement = (
  typistGroupNames: string[] | string
): JSX.Element[] | string => {
  if (typeof typistGroupNames === "string") {
    return typistGroupNames;
  }
  return typistGroupNames.map((v, i) => (
    <span key={v}>
      {v}
      {i !== typistGroupNames.length - 1 && <br />}
    </span>
  ));
};

const isAlertElement = (
  licenseStatus: string
): {
  isAlertLicenseStatus: boolean;
  isAlertRemaining: boolean;
} => {
  // licenseStatusの型がLicenseStatusTypeでない場合(Normal)、どちらもfalseにする
  if (isLicenseStatusType(licenseStatus) === false) {
    return {
      isAlertLicenseStatus: false,
      isAlertRemaining: false,
    };
  }
  // licenseStatusがNOLICENSEの場合、isAlertLicenseStatusをtrueにする(Remainingはハイフン)
  if (licenseStatus === LICENSE_STATUS.NOLICENSE) {
    return {
      isAlertLicenseStatus: true,
      isAlertRemaining: false,
    };
  }
  // licenseStatusがALERTの場合、どちらもtrueにする
  if (licenseStatus === LICENSE_STATUS.ALERT) {
    return {
      isAlertLicenseStatus: true,
      isAlertRemaining: true,
    };
  }
  // licenseStatusがRENEWの場合、どちらもfalseにする
  return {
    isAlertLicenseStatus: false,
    isAlertRemaining: false,
  };
};

export default UserListPage;
