import { UpdateTokenTimer } from "components/auth/updateTokenTimer";
import Footer from "components/footer";
import Header from "components/header";
import React, { useCallback, useEffect, useState } from "react";
import { getTranslationID } from "translation";
import styles from "styles/app.module.scss";
import undo from "assets/images/undo.svg";
import worktype_add from "assets/images/worktype_add.svg";
import progress_activit from "assets/images/progress_activit.svg";
import { useTranslation } from "react-i18next";
import { useDispatch, useSelector } from "react-redux";
import {
  changeSelectedId,
  changeWorktypeId,
  changeDescription,
  listWorktypesAsync,
  updateActiveWorktypeAsync,
  selectIsLoading,
  selectWorktypes,
  selectActiveWorktypeId,
  deleteWorktypeAsync,
} from "features/workflow/worktype";
import { AppDispatch } from "app/store";
import { selectDelegationAccessToken } from "features/auth/selectors";
import { DelegationBar } from "components/delegate";
import { useNavigate } from "react-router-dom";
import { AddWorktypeIdPopup } from "./addWorktypeIdPopup";
import { EditWorktypeIdPopup } from "./editWorktypeIdPopup";
import { EditOptionItemsPopup } from "./editOptionItemsPopup";

const WorktypeIdSettingPage: React.FC = (): JSX.Element => {
  const dispatch: AppDispatch = useDispatch();
  const [t] = useTranslation();
  const navigate = useNavigate();
  // 代行操作用のトークンを取得する
  const delegationAccessToken = useSelector(selectDelegationAccessToken);
  const isLoading = useSelector(selectIsLoading);
  const worktypes = useSelector(selectWorktypes);
  const activeWorktypeId = useSelector(selectActiveWorktypeId);

  const [selectedRow, setSelectedRow] = useState<number>(NaN);

  // 追加Popupの表示制御
  const [isShowAddPopup, setIsShowAddPopup] = useState<boolean>(false);
  // 編集Popupの表示制御
  const [isShowEditPopup, setIsShowEditPopup] = useState<boolean>(false);
  const [isShowEditOptionItemPopup, setIsShowEditOptionItemPopup] =
    useState<boolean>(false);

  // ActiveWorktypeIDのセレクトボックス表示の値
  const [selectedActiveWorktypeId, setSelectedActiveWorktypeId] = useState<
    number | undefined
  >(undefined);

  // 初期表示
  useEffect(() => {
    dispatch(listWorktypesAsync());
  }, [dispatch]);

  // APIから取得したactiveWorktypeIdを画面表示に反映
  useEffect(() => {
    setSelectedActiveWorktypeId(activeWorktypeId);
  }, [activeWorktypeId]);

  // TODO:このsetTimeoutを使った実装は暫定対応。useEffectで無理やり処理しているので修正予定
  // ActiveWorktypeIDのセレクトボックス変更時（セレクトボックスに表示するActiveWorktypeIDの変更時）
  useEffect(() => {
    // 画面表示の変更後にダイアログを表示するため、setTimeoutを使用
    const timeout = setTimeout(async () => {
      if (selectedActiveWorktypeId === activeWorktypeId) {
        return;
      }
      // ダイアログ確認
      if (
        // eslint-disable-next-line no-alert
        !window.confirm(t(getTranslationID("common.message.dialogConfirm")))
      ) {
        setSelectedActiveWorktypeId(activeWorktypeId);
        return;
      }
      const { meta } = await dispatch(
        updateActiveWorktypeAsync({ id: selectedActiveWorktypeId })
      );

      if (meta.requestStatus === "fulfilled") {
        dispatch(listWorktypesAsync());
      } else {
        setSelectedActiveWorktypeId(activeWorktypeId);
      }
    }, 0);
    return () => {
      clearTimeout(timeout);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedActiveWorktypeId]);

  // 削除ボタン押下時の処理
  const onDeleteWoktype = useCallback(
    async (worktypeId: number) => {
      if (
        /* eslint-disable-next-line no-alert */
        !window.confirm(t(getTranslationID("common.message.dialogConfirm")))
      ) {
        return;
      }
      const { meta } = await dispatch(deleteWorktypeAsync({ worktypeId }));
      if (meta.requestStatus === "fulfilled") {
        dispatch(listWorktypesAsync());
      }
    },
    [dispatch, t]
  );

  return (
    <>
      <AddWorktypeIdPopup
        onClose={() => {
          setIsShowAddPopup(false);
        }}
        isOpen={isShowAddPopup}
      />
      <EditWorktypeIdPopup
        onClose={() => {
          setIsShowEditPopup(false);
        }}
        isOpen={isShowEditPopup}
      />
      <EditOptionItemsPopup
        onClose={() => {
          setIsShowEditOptionItemPopup(false);
        }}
        isOpen={isShowEditOptionItemPopup}
      />
      <div
        className={`${styles.wrap} ${
          delegationAccessToken ? styles.manage : ""
        }`}
      >
        {delegationAccessToken && <DelegationBar />}
        <Header />
        <UpdateTokenTimer />
        <main className={styles.main}>
          <div>
            <div className={styles.pageHeader}>
              <h1 className={styles.pageTitle}>
                {t(getTranslationID("workflowPage.label.title"))}
              </h1>
              <p className={styles.pageTx}>
                {t(getTranslationID("worktypeIdSetting.label.title"))}
              </p>
            </div>
            <section className={styles.workflow}>
              <div>
                <ul className={`${styles.menuAction} ${styles.worktype}`}>
                  <li>
                    {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */}
                    <a
                      onClick={() => navigate("/workflow")}
                      className={`${styles.menuLink} ${styles.isActive}`}
                    >
                      <img src={undo} alt="" className={styles.menuIcon} />
                      {t(getTranslationID("common.label.return"))}
                    </a>
                  </li>
                  <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={() => {
                        setIsShowAddPopup(true);
                      }}
                    >
                      <img
                        src={worktype_add}
                        alt=""
                        className={styles.menuIcon}
                      />
                      {t(
                        getTranslationID(
                          "worktypeIdSetting.label.addWorktypeId"
                        )
                      )}
                    </a>
                  </li>
                  <li className={`${styles.selectMenu} ${styles.form}`}>
                    {`${t(
                      getTranslationID(
                        "worktypeIdSetting.label.activeWorktypeId"
                      )
                    )}:`}
                    <select
                      name="Active Worktype"
                      className={styles.formInput}
                      value={selectedActiveWorktypeId ?? ""}
                      onChange={(e) => {
                        const { value } = e.target;
                        const active = value === "" ? undefined : Number(value);
                        setSelectedActiveWorktypeId(active);
                      }}
                      required
                    >
                      <option value="">
                        {`-- ${t(
                          getTranslationID("common.label.notSelected")
                        )} --`}
                      </option>
                      {worktypes?.map((worktype) => (
                        <option key={worktype.id} value={worktype.id}>
                          {worktype.worktypeId}
                        </option>
                      ))}
                    </select>
                  </li>
                </ul>
                <table className={`${styles.table} ${styles.worktype}`}>
                  <tr className={styles.tableHeader}>
                    <th className={styles.noLine}>
                      {t(
                        getTranslationID("worktypeIdSetting.label.worktypeId")
                      )}
                    </th>
                    <th className={styles.noLine}>
                      {t(
                        getTranslationID("worktypeIdSetting.label.description")
                      )}
                    </th>
                    <th>{/** empty th */}</th>
                  </tr>
                  {worktypes?.map((worktype) => (
                    <tr
                      key={worktype.id}
                      className={
                        worktype.id === selectedRow ? styles.isSelected : ""
                      }
                      onMouseEnter={() => {
                        setSelectedRow(worktype.id);
                      }}
                      onMouseLeave={() => {
                        setSelectedRow(NaN);
                      }}
                    >
                      <td>{worktype.worktypeId}</td>
                      <td>{worktype.description}</td>
                      <td>
                        <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.menuLink} ${styles.isActive}`}
                              onClick={() => {
                                dispatch(changeSelectedId({ id: worktype.id }));
                                dispatch(
                                  changeWorktypeId({
                                    worktypeId: worktype.worktypeId,
                                  })
                                );
                                dispatch(
                                  changeDescription({
                                    description: worktype.description,
                                  })
                                );
                                setIsShowEditPopup(true);
                              }}
                            >
                              {t(getTranslationID("common.label.edit"))}
                            </a>
                          </li>
                          <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={() => {
                                dispatch(changeSelectedId({ id: worktype.id }));
                                setIsShowEditOptionItemPopup(true);
                              }}
                            >
                              {t(
                                getTranslationID(
                                  "worktypeIdSetting.label.optionItem"
                                )
                              )}
                            </a>
                          </li>
                          <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={() => onDeleteWoktype(worktype.id)}
                            >
                              {t(getTranslationID("common.label.delete"))}
                            </a>
                          </li>
                        </ul>
                      </td>
                    </tr>
                  ))}
                </table>
                {!isLoading &&
                  (worktypes === undefined || worktypes.length === 0) && (
                    <p
                      style={{
                        margin: "10px",
                        textAlign: "center",
                        width: "1000px",
                      }}
                    >
                      {t(getTranslationID("common.message.listEmpty"))}
                    </p>
                  )}
                {isLoading && (
                  <img
                    src={progress_activit}
                    className={styles.icLoading}
                    alt="Loading"
                  />
                )}
              </div>
            </section>
          </div>
        </main>
        <Footer />
      </div>
    </>
  );
};

export default WorktypeIdSettingPage;
