/* eslint-disable jsx-a11y/control-has-associated-label */
import React, { useCallback, useEffect } from "react";
import { UpdateTokenTimer } from "components/auth/updateTokenTimer";
import Footer from "components/footer";
import Header from "components/header";
import styles from "styles/app.module.scss";
import { getTranslationID } from "translation";
import { useTranslation } from "react-i18next";
import { AppDispatch } from "app/store";
import { useDispatch, useSelector } from "react-redux";
import {
  LIMIT_ORDER_HISORY_NUM,
  STATUS,
  getLicenseOrderHistoriesAsync,
  selectCurrentPage,
  selectIsLoading,
  selectOrderHisory,
  selectTotal,
  selectTotalPage,
  issueLicenseAsync,
  selectOffset,
  savePageInfo,
  selectCompanyName,
} from "features/license/licenseOrderHistory";
import { selectSelectedRow } from "features/license/partnerLicense";
import undo from "../../assets/images/undo.svg";
import history from "../../assets/images/history.svg";
import progress_activit from "../../assets/images/progress_activit.svg";

interface LicenseOrderHistoryProps {
  onReturn: () => void;
}
export const LicenseOrderHistory: React.FC<LicenseOrderHistoryProps> = (
  props
): JSX.Element => {
  const { onReturn } = props;
  const dispatch: AppDispatch = useDispatch();
  const [t] = useTranslation();
  const total = useSelector(selectTotal);
  const totalPage = useSelector(selectTotalPage);
  const offset = useSelector(selectOffset);
  const currentPage = useSelector(selectCurrentPage);
  const isLoading = useSelector(selectIsLoading);
  const selectedRow = useSelector(selectSelectedRow);

  // Return押下時の処理
  const returnGui = useCallback(() => {
    if (isLoading) {
      return;
    }
    onReturn();
  }, [isLoading, onReturn]);

  // issue,issueCancel,orderCancelボタンの処理終了時の情報更新用
  const UpdateHistoriesList = () => {
    dispatch(
      getLicenseOrderHistoriesAsync({
        limit: LIMIT_ORDER_HISORY_NUM,
        offset,
      })
    );
  };

  // issueボタンを押下時の処理
  const issueLicense = useCallback(
    async (poNumber: string) => {
      // ダイアログ確認
      // eslint-disable-next-line no-alert
      if (window.confirm(t(getTranslationID("common.message.dialogConfirm")))) {
        // 注文APIの呼び出し
        if (selectedRow) {
          const { meta } = await dispatch(
            issueLicenseAsync({
              orderedAccountId: selectedRow.accountId,
              poNumber,
            })
          );
          if (meta.requestStatus === "fulfilled") {
            UpdateHistoriesList();
          }
        }
      }
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [dispatch]
  );

  // ページネーションのボタンクリック時のアクション
  const movePage = (targetOffset: number) => {
    dispatch(
      savePageInfo({ limit: LIMIT_ORDER_HISORY_NUM, offset: targetOffset })
    );
  };

  // apiからの値取得関係
  const licenseOrderHistory = useSelector(selectOrderHisory);
  const companyName = useSelector(selectCompanyName);

  useEffect(() => {
    dispatch(
      getLicenseOrderHistoriesAsync({
        limit: LIMIT_ORDER_HISORY_NUM,
        offset,
      })
    );
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dispatch, currentPage]);

  return (
    <div className={styles.wrap}>
      <Header userName="XXXXXX" />

      <UpdateTokenTimer />
      <main className={styles.main}>
        <div>
          <div className={styles.pageHeader}>
            <h1 className={styles.pageTitle}>
              {t(getTranslationID("orderHistoriesPage.label.title"))}
            </h1>
          </div>
          <section className={styles.license}>
            <div>
              <h2>{companyName}</h2>
              <p className={styles.brCrumb}>
                <img src={history} alt="" className={styles.tlIcon} />
                {t(getTranslationID("orderHistoriesPage.label.orderHistory"))}
              </p>

              <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} ${styles.isActive}`}
                    onClick={returnGui}
                  >
                    <img src={undo} alt="" className={styles.menuIcon} />
                    {t(getTranslationID("orderHistoriesPage.label.return"))}
                  </a>
                </li>
              </ul>
              <div className={styles.tableWrap}>
                <table className={`${styles.table} ${styles.history}`}>
                  <tr className={styles.tableHeader}>
                    <th>
                      {t(
                        getTranslationID("orderHistoriesPage.label.orderDate")
                      )}
                    </th>
                    <th>
                      {t(
                        getTranslationID("orderHistoriesPage.label.issueDate")
                      )}
                    </th>
                    <th>
                      {t(
                        getTranslationID(
                          "orderHistoriesPage.label.numberOfOrder"
                        )
                      )}
                    </th>
                    <th>
                      {t(getTranslationID("orderHistoriesPage.label.poNumber"))}
                    </th>
                    <th className={styles.noLine}>
                      {t(getTranslationID("orderHistoriesPage.label.status"))}
                    </th>
                    <th className={styles.noLine} />
                  </tr>
                  {!isLoading &&
                    licenseOrderHistory.length !== 0 &&
                    licenseOrderHistory.map((x) => (
                      // eslint-disable-next-line react/jsx-key
                      <tr>
                        <td>{x.orderDate}</td>
                        <td>{x.issueDate ? x.issueDate : "-"}</td>
                        <td>{x.numberOfOrder}</td>
                        <td>{x.poNumber}</td>
                        <td>
                          {(() => {
                            switch (x.status) {
                              case STATUS.ISSUE_REQESTING:
                                return t(
                                  getTranslationID(
                                    "orderHistoriesPage.label.issueRequesting"
                                  )
                                );
                              case STATUS.ISSUED:
                                return t(
                                  getTranslationID(
                                    "orderHistoriesPage.label.issued"
                                  )
                                );
                              case STATUS.ORDER_CANCELED:
                                return t(
                                  getTranslationID(
                                    "orderHistoriesPage.label.orderCanceled"
                                  )
                                );
                              default:
                                return "";
                            }
                          })()}
                        </td>
                        <td>
                          {!selectedRow && (
                            <ul
                              className={`${styles.menuAction} ${styles.inTable}`}
                            >
                              <li>
                                <a
                                  className={`${styles.menuLink} ${
                                    x.status === STATUS.ISSUE_REQESTING
                                      ? styles.isActive
                                      : ""
                                  }`}
                                >
                                  {t(
                                    getTranslationID(
                                      "orderHistoriesPage.label.orderCancel"
                                    )
                                  )}
                                </a>
                              </li>
                            </ul>
                          )}
                          {selectedRow && (
                            <ul
                              className={`${styles.menuAction} ${styles.inTable}`}
                            >
                              <li>
                                {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */}
                                <a
                                  className={`${styles.colorLink} ${
                                    x.status === STATUS.ISSUE_REQESTING
                                      ? styles.isActive
                                      : ""
                                  }`}
                                  onClick={(event) => {
                                    event.preventDefault();
                                    issueLicense(x.poNumber);
                                  }}
                                >
                                  {t(
                                    getTranslationID(
                                      "orderHistoriesPage.label.issue"
                                    )
                                  )}
                                </a>
                              </li>
                              <li>
                                <a
                                  className={`${styles.menuLink} ${
                                    x.status === STATUS.ISSUED
                                      ? styles.isActive
                                      : ""
                                  }`}
                                >
                                  {t(
                                    getTranslationID(
                                      "orderHistoriesPage.label.issueCancel"
                                    )
                                  )}
                                </a>
                              </li>
                            </ul>
                          )}
                        </td>
                      </tr>
                    ))}
                </table>
              </div>
              {isLoading && (
                <img
                  style={{ position: "sticky" }}
                  src={progress_activit}
                  className={styles.icLoading}
                  alt="Loading"
                />
              )}
              {/** pagenation */}
              <div className={`${styles.pagenation} ${styles.widthMid}`}>
                <nav className={styles.pagenationNav}>
                  <span className={styles.pagenationTotal}>{`${total} ${t(
                    getTranslationID("orderHistoriesPage.label.histories")
                  )}`}</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_ORDER_HISORY_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_ORDER_HISORY_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_ORDER_HISORY_NUM);
                    }}
                  >
                    »
                  </a>
                </nav>
              </div>
            </div>
          </section>
        </div>
      </main>
      <Footer />
    </div>
  );
};

export default LicenseOrderHistory;
