import React, { useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
import styles from "styles/app.module.scss";
import { useDispatch, useSelector } from "react-redux";
import {
  addWorktypeAsync,
  changeDescription,
  changeWorktypeId,
  cleanupWorktype,
  listWorktypesAsync,
  selectDescription,
  selectHasErrorWorktypeId,
  selectIsAddLoading,
  selectWorktypeId,
} from "features/workflow/worktype";
import { AppDispatch } from "app/store";
import { getTranslationID } from "translation";
import close from "../../assets/images/close.svg";
import progress_activit from "../../assets/images/progress_activit.svg";

// popupのpropsの型定義
interface AddWorktypeIdPopupProps {
  onClose: () => void;
  isOpen: boolean;
}

export const AddWorktypeIdPopup: React.FC<AddWorktypeIdPopupProps> = (
  props: AddWorktypeIdPopupProps
): JSX.Element => {
  const { onClose, isOpen } = props;
  const [t] = useTranslation();
  const dispatch: AppDispatch = useDispatch();

  const isAddLoading = useSelector(selectIsAddLoading);
  const worktypeId = useSelector(selectWorktypeId);
  const description = useSelector(selectDescription);
  // 追加ボタンを押したかどうか
  const [isPushAddButton, setIsPushAddButton] = useState<boolean>(false);
  // WorktypeIdのバリデーションチェック
  const { hasIncorrectPatternWorktypeId, isEmptyWorktypeId } = useSelector(
    selectHasErrorWorktypeId
  );

  // ×ボタンを押した時の処理
  const closePopup = useCallback(() => {
    if (isAddLoading) {
      return;
    }
    dispatch(cleanupWorktype());
    setIsPushAddButton(false);
    onClose();
  }, [onClose, dispatch, isAddLoading]);

  // 追加ボタンを押した時の処理
  const addWorktypeId = useCallback(async () => {
    setIsPushAddButton(true);
    if (isEmptyWorktypeId || hasIncorrectPatternWorktypeId) {
      return;
    }
    const { meta } = await dispatch(addWorktypeAsync());
    if (meta.requestStatus === "fulfilled") {
      dispatch(listWorktypesAsync());
      closePopup();
    }
  }, [closePopup, dispatch, hasIncorrectPatternWorktypeId, isEmptyWorktypeId]);

  return (
    <div className={`${styles.modal} ${isOpen ? styles.isShow : ""}`}>
      <div className={styles.modalBox}>
        <p className={styles.modalTitle}>
          {t(getTranslationID("worktypeIdSetting.label.addWorktypeId"))}
          {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-noninteractive-element-interactions */}
          <img
            src={close}
            className={styles.modalTitleIcon}
            alt="close"
            onClick={closePopup}
          />
        </p>
        <form className={styles.form}>
          <dl className={`${styles.formList} ${styles.hasbg}`}>
            <dt className={styles.formTitle} />
            <dt>{t(getTranslationID("worktypeIdSetting.label.worktypeId"))}</dt>
            <dd>
              <input
                type="text"
                size={40}
                maxLength={16}
                value={worktypeId ?? ""}
                className={styles.formInput}
                onChange={(e) => {
                  dispatch(changeWorktypeId({ worktypeId: e.target.value }));
                }}
              />
              {isPushAddButton && isEmptyWorktypeId && (
                <span className={styles.formError}>
                  {t(getTranslationID("common.message.inputEmptyError"))}
                </span>
              )}
              {isPushAddButton && hasIncorrectPatternWorktypeId && (
                <span className={styles.formError}>
                  {t(
                    getTranslationID(
                      "worktypeIdSetting.message.worktypeIdIncorrectError"
                    )
                  )}
                </span>
              )}
              <span
                style={{ whiteSpace: "pre-line" }}
                className={styles.formComment}
              >
                {t(getTranslationID("worktypeIdSetting.label.worktypeIdTerms"))}
              </span>
            </dd>
            <dt className={styles.overLine}>
              {t(
                getTranslationID("worktypeIdSetting.label.descriptionOptional")
              )}
            </dt>
            <dd className={styles.last}>
              <input
                type="text"
                size={40}
                maxLength={255}
                value={description ?? ""}
                className={styles.formInput}
                onChange={(e) => {
                  dispatch(
                    changeDescription({
                      description:
                        e.target.value === "" ? undefined : e.target.value,
                    })
                  );
                }}
              />
            </dd>
            <dd className={`${styles.full} ${styles.alignCenter}`}>
              <input
                type="button"
                name="Add Worktype"
                value={t(
                  getTranslationID("worktypeIdSetting.label.addWorktype")
                )}
                className={`${styles.formSubmit} ${styles.marginBtm1} ${
                  !isAddLoading ? styles.isActive : ""
                }`}
                onClick={addWorktypeId}
              />
              {isAddLoading && (
                <img
                  src={progress_activit}
                  className={styles.icLoading}
                  alt="Loading"
                />
              )}
            </dd>
          </dl>
        </form>
      </div>
    </div>
  );
};
