/* 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,
} 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 currentPage = useSelector(selectCurrentPage);
  const isLoading = useSelector(selectIsLoading);
  const selectedRow = useSelector(selectSelectedRow);

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

  // ページネーションのボタンクリック時のアクション
  const getFirstPage = useCallback(() => {
    dispatch(
      getLicenseOrderHistoriesAsync({
        limit: LIMIT_ORDER_HISORY_NUM,
        offset: 0,
      })
    );
  }, [dispatch]);

  const getLastPage = useCallback(() => {
    const lastPageOffset = (totalPage - 1) * LIMIT_ORDER_HISORY_NUM;
    dispatch(
      getLicenseOrderHistoriesAsync({
        limit: LIMIT_ORDER_HISORY_NUM,
        offset: lastPageOffset,
      })
    );
  }, [dispatch, totalPage]);

  const getPrevPage = useCallback(() => {
    const prevPageOffset = (currentPage - 2) * LIMIT_ORDER_HISORY_NUM;
    dispatch(
      getLicenseOrderHistoriesAsync({
        limit: LIMIT_ORDER_HISORY_NUM,
        offset: prevPageOffset,
      })
    );
  }, [dispatch, currentPage]);

  const getNextPage = useCallback(() => {
    const nextPageOffset = currentPage * LIMIT_ORDER_HISORY_NUM;
    dispatch(
      getLicenseOrderHistoriesAsync({
        limit: LIMIT_ORDER_HISORY_NUM,
        offset: nextPageOffset,
      })
    );
  }, [dispatch, currentPage]);

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

  useEffect(() => {
    dispatch(
      getLicenseOrderHistoriesAsync({
        limit: LIMIT_ORDER_HISORY_NUM,
        offset: 0,
      })
    );
  }, [dispatch]);

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

      <UpdateTokenTimer />
      <main className={styles.main}>
        <div className="">
          <div className={styles.pageHeader}>
            <h1 className={styles.pageTitle}>
              {t(getTranslationID("orderHistoriesPage.label.title"))}
            </h1>
          </div>
          <section className={styles.license}>
            <div>
              <h2 className="">
                {t(getTranslationID("orderHistoriesPage.label.subTitle"))}
                <p className={styles.brCrumb}>
                  <img src={history} alt="" className={styles.tlIcon} />
                  {t(getTranslationID("orderHistoriesPage.label.orderHistory"))}
                </p>
              </h2>
              <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} />
                    <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}</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 === undefined &&
                            x.status === STATUS.ISSUE_REQESTING && (
                              <ul
                                className={`${styles.menuAction} ${styles.inTable}`}
                              >
                                <li>
                                  <a
                                    href=""
                                    className={`${styles.menuLink} ${styles.isActive}`}
                                  >
                                    {t(
                                      getTranslationID(
                                        "orderHistoriesPage.label.orderCancel"
                                      )
                                    )}
                                  </a>
                                </li>
                              </ul>
                            )}
                          {selectedRow !== undefined &&
                            x.status === STATUS.ISSUE_REQESTING && (
                              <ul
                                className={`${styles.menuAction} ${styles.inTable}`}
                              >
                                <li>
                                  <a
                                    href=""
                                    className={`${styles.colorLink} ${styles.isActive}`}
                                  >
                                    {t(
                                      getTranslationID(
                                        "orderHistoriesPage.label.issue"
                                      )
                                    )}
                                  </a>
                                </li>
                              </ul>
                            )}
                          {selectedRow !== undefined &&
                            x.status === STATUS.ISSUED && (
                              <ul
                                className={`${styles.menuAction} ${styles.inTable}`}
                              >
                                <li>
                                  <a
                                    href=""
                                    className={`${styles.menuLink} ${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}>
                <nav className={styles.pagenationNav}>
                  <span className={styles.pagenationTotal}>{`${total} ${t(
                    getTranslationID("orderHistoriesPage.label.title")
                  )}`}</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={getFirstPage}
                  >
                    «
                  </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={getPrevPage}
                  >
                    ‹
                  </a>
                  {`${currentPage} of ${totalPage}`}
                  {/* 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={getNextPage}
                  >
                    ›
                  </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={getLastPage}
                  >
                    »
                  </a>
                </nav>
              </div>
            </div>
          </section>
        </div>
      </main>
      <Footer />
    </div>
  );
};

export default LicenseOrderHistory;
