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 {
  changeDealer,
  changeDealerPermission,
  changePrimaryAdministrator,
  changeSecondryAdministrator,
  getAccountRelationsAsync,
  selectAccountInfo,
  selectDealers,
  selectIsLoading,
  selectUpdateAccountInfo,
  selectUsers,
  updateAccountInfoAsync,
} from "features/account/index";
import { useTranslation } from "react-i18next";
import { getTranslationID } from "translation";
import { TIERS } from "components/auth/constants";
import { isApproveTier } from "features/auth";
import { DeleteAccountPopup } from "./deleteAccountPopup";
import progress_activit from "../../assets/images/progress_activit.svg";

const AccountPage: React.FC = (): JSX.Element => {
  const dispatch: AppDispatch = useDispatch();
  const [t] = useTranslation();
  const viewInfo = useSelector(selectAccountInfo);
  const dealers = useSelector(selectDealers);
  const users = useSelector(selectUsers);
  const isLoading = useSelector(selectIsLoading);
  const updateAccountInfo = useSelector(selectUpdateAccountInfo);

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

  const [isDeleteAccountPopupOpen, setIsDeleteAccountPopupOpen] =
    useState(false);

  const onDeleteAccountOpen = useCallback(() => {
    setIsDeleteAccountPopupOpen(true);
  }, [setIsDeleteAccountPopupOpen]);

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

  // 画面起動時
  useEffect(() => {
    dispatch(getAccountRelationsAsync());
  }, [dispatch]);

  const [isPushSaveChangesButton, setIsPushSaveChangesButton] =
    useState<boolean>(false);
  const [isEmptyPrimaryAdmin, setIsEmptyPrimaryAdmin] =
    useState<boolean>(false);
  // SaveChanges押下時
  const onSaveChangesButton = useCallback(async () => {
    setIsPushSaveChangesButton(true);
    if (!updateAccountInfo.primaryAdminUserId) {
      setIsEmptyPrimaryAdmin(true);
      return;
    }
    await dispatch(updateAccountInfoAsync(updateAccountInfo));
    dispatch(getAccountRelationsAsync());
    setIsEmptyPrimaryAdmin(false);
    setIsPushSaveChangesButton(false);
  }, [dispatch, updateAccountInfo]);

  return (
    <>
      {isDeleteAccountPopupOpen && (
        <DeleteAccountPopup
          onClose={() => {
            setIsDeleteAccountPopupOpen(false);
          }}
        />
      )}
      <div className={styles.wrap}>
        <Header />
        <UpdateTokenTimer />
        <main className={styles.main}>
          <div>
            <div className={styles.pageHeader}>
              <h1 className={styles.pageTitle}>
                {t(getTranslationID("accountPage.label.title"))}
              </h1>
            </div>

            <section className={styles.account}>
              <div className={styles.boxFlex}>
                <ul className={`${styles.menuAction} ${styles.box100}`}>
                  <li>
                    <a
                      href="account_setting.html"
                      className={`${styles.menuLink} ${styles.isActive}`}
                    >
                      <img
                        src="images/file_delete.svg"
                        alt=""
                        className={styles.menuIcon}
                      />
                      {t(
                        getTranslationID("accountPage.label.fileDeleteSetting")
                      )}
                    </a>
                  </li>
                </ul>

                <div className={styles.marginRgt3}>
                  <dl className={styles.listVertical}>
                    <h4 className={styles.listHeader}>
                      {t(
                        getTranslationID("accountPage.label.accountInformation")
                      )}
                    </h4>
                    <dt>
                      {t(getTranslationID("accountPage.label.companyName"))}
                    </dt>
                    <dd>{viewInfo.account.companyName}</dd>
                    <dt>
                      {t(getTranslationID("accountPage.label.accountID"))}
                    </dt>
                    <dd>{viewInfo.account.accountId}</dd>
                    <dt>
                      {t(getTranslationID("accountPage.label.yourCategory"))}
                    </dt>
                    <dd>{tierNames[viewInfo.account.tier]}</dd>
                    <dt>
                      {t(getTranslationID("accountPage.label.yourCountry"))}
                    </dt>
                    <dd>{viewInfo.account.country}</dd>
                    <dt>
                      {t(getTranslationID("accountPage.label.yourDealer"))}
                    </dt>
                    {isTier5 && !viewInfo.account.parentAccountName && (
                      <dd className={styles.form}>
                        <select
                          className={styles.formInput}
                          required
                          onChange={(event) => {
                            dispatch(
                              changeDealer({
                                parentAccountId:
                                  dealers.find(
                                    (x) => x.name === event.target.value
                                  )?.id || undefined,
                              })
                            );
                          }}
                        >
                          <option value="" hidden>
                            {`-- ${t(
                              getTranslationID("accountPage.label.selectDealer")
                            )} --`}
                          </option>
                          <option value="">
                            {`-- ${t(
                              getTranslationID("common.label.notSelected")
                            )} --`}
                          </option>
                          {dealers.map((x) => (
                            <option key={x.name} value={x.name}>
                              {x.name}
                            </option>
                          ))}
                        </select>
                      </dd>
                    )}
                    {(!isTier5 || viewInfo.account.parentAccountName) && (
                      <dd>{viewInfo.account.parentAccountName ?? "-"}</dd>
                    )}
                    <dt>
                      {t(
                        getTranslationID("accountPage.label.dealerManagement")
                      )}
                    </dt>
                    {isTier5 && (
                      <dd>
                        {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}
                        <label>
                          <input
                            type="checkbox"
                            className={styles.formCheck}
                            checked={updateAccountInfo.delegationPermission}
                            onChange={(e) => {
                              dispatch(
                                changeDealerPermission({
                                  delegationPermission: e.target.checked,
                                })
                              );
                            }}
                          />
                        </label>
                      </dd>
                    )}
                    {!isTier5 && <dd>-</dd>}
                  </dl>
                </div>

                <div>
                  <dl className={styles.listVertical}>
                    <h4 className={styles.listHeader}>
                      {t(
                        getTranslationID(
                          "accountPage.label.administratorInformation"
                        )
                      )}
                    </h4>
                    <dt>
                      {t(
                        getTranslationID(
                          "accountPage.label.primaryAdministrator"
                        )
                      )}
                    </dt>
                    <dd>
                      {
                        users.find(
                          (x) => x.id === viewInfo.account.primaryAdminUserId
                        )?.name
                      }
                    </dd>
                    <dt>
                      {t(getTranslationID("accountPage.label.emailAddress"))}
                    </dt>
                    <dd className={styles.form}>
                      <select
                        className={styles.formInput}
                        required
                        onChange={(event) => {
                          dispatch(
                            changePrimaryAdministrator({
                              primaryAdminUserId:
                                users.find(
                                  (x) => x.email === event.target.value
                                )?.id || 0,
                            })
                          );
                        }}
                      >
                        <option
                          hidden
                          value={
                            users.find(
                              (x) =>
                                x.id === viewInfo.account.primaryAdminUserId
                            )?.email || undefined
                          }
                        >
                          {
                            users.find(
                              (x) =>
                                x.id === viewInfo.account.primaryAdminUserId
                            )?.email
                          }
                        </option>
                        {users.map((x) => (
                          <option key={x.email} value={x.email}>
                            {x.email}
                          </option>
                        ))}
                      </select>
                      {isPushSaveChangesButton && isEmptyPrimaryAdmin && (
                        <span className={styles.formError}>
                          {" "}
                          {t(
                            getTranslationID(
                              "signupPage.message.inputEmptyError"
                            )
                          )}
                        </span>
                      )}
                    </dd>
                    <dt>
                      {t(
                        getTranslationID(
                          "accountPage.label.secondaryAdministrator"
                        )
                      )}
                    </dt>
                    <dd>
                      {
                        users.find(
                          (x) => x.id === viewInfo.account.secondryAdminUserId
                        )?.name
                      }
                    </dd>
                    <dt>
                      {t(getTranslationID("accountPage.label.emailAddress"))}
                    </dt>
                    <dd className={styles.form}>
                      <select
                        className={styles.formInput}
                        required
                        onChange={(event) => {
                          dispatch(
                            changeSecondryAdministrator({
                              secondryAdminUserId:
                                users.find(
                                  (x) => x.email === event.target.value
                                )?.id ?? undefined,
                            })
                          );
                        }}
                      >
                        <option
                          hidden
                          value={
                            viewInfo.account.secondryAdminUserId
                              ? users.find(
                                  (x) =>
                                    x.id ===
                                    viewInfo.account.secondryAdminUserId
                                )?.email
                              : undefined
                          }
                        >
                          {viewInfo.account.secondryAdminUserId
                            ? users.find(
                                (x) =>
                                  x.id === viewInfo.account.secondryAdminUserId
                              )?.email
                            : `-- ${t(
                                getTranslationID(
                                  "accountPage.label.selectSecondaryAdministrator"
                                )
                              )} --`}
                        </option>
                        <option value="">
                          {`-- ${t(
                            getTranslationID("common.label.notSelected")
                          )} --`}
                        </option>
                        {users.map((x) => (
                          <option key={x.email} value={x.email}>
                            {x.email}
                          </option>
                        ))}
                      </select>
                    </dd>
                  </dl>
                </div>
                <div className={`${styles.box100} ${styles.alignLeft} `}>
                  <input
                    type="submit"
                    name="submit"
                    value={t(getTranslationID("accountPage.label.saveChanges"))}
                    className={`${styles.formSubmit} ${
                      !isLoading ? styles.isActive : ""
                    }
                `}
                    onClick={onSaveChangesButton}
                    data-tag="savechanges-account"
                  />
                  <img
                    style={{ display: isLoading ? "inline" : "none" }}
                    src={progress_activit}
                    className={styles.icLoading}
                    alt="Loading"
                  />
                </div>
              </div>
              {isTier5 && (
                <ul className={styles.linkBottom}>
                  <li>
                    {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */}
                    <a
                      className={styles.linkTx}
                      onClick={onDeleteAccountOpen}
                      data-tag="open-delete-account-popup"
                    >
                      {t(getTranslationID("accountPage.label.deleteAccount"))}
                    </a>
                  </li>
                </ul>
              )}
            </section>
          </div>
        </main>
        <Footer />
      </div>
    </>
  );
};

export default AccountPage;
