import React, { useCallback, useEffect, useState } from "react";
import { AppDispatch } from "app/store";
import progress_activit from "assets/images/progress_activit.svg";
import {
  addAssignee,
  removeAssignee,
  changeAuthor,
  changeTemplate,
  changeWorktype,
  clearWorkflow,
  selectIsAddLoading,
  selectWorkflowAssinee,
  selectWorkflowError,
  selectWorkflowRelations,
} from "features/workflow";
import {
  createWorkflowAsync,
  getworkflowRelationsAsync,
  listWorkflowAsync,
} from "features/workflow/operations";
import { useTranslation } from "react-i18next";
import { useDispatch, useSelector } from "react-redux";
import styles from "styles/app.module.scss";
import { getTranslationID } from "translation";
import close from "../../assets/images/close.svg";

interface AddWorkflowPopupProps {
  onClose: () => void;
}

export const AddWorkflowPopup: React.FC<AddWorkflowPopupProps> = (
  props
): JSX.Element => {
  const { onClose } = props;
  const dispatch: AppDispatch = useDispatch();
  const [t] = useTranslation();
  // 保存ボタンを押したかどうか
  const [isPushAddButton, setIsPushAddButton] = useState<boolean>(false);

  const workflowRelations = useSelector(selectWorkflowRelations);
  const { poolAssignees, selectedAssignees } = useSelector(
    selectWorkflowAssinee
  );
  const isLoading = useSelector(selectIsAddLoading);
  const { hasAuthorIdEmptyError, hasSelectedWorkflowAssineeEmptyError } =
    useSelector(selectWorkflowError);
  useEffect(() => {
    dispatch(getworkflowRelationsAsync());
    // ポップアップのアンマウント時に初期化を行う
    return () => {
      dispatch(clearWorkflow());
      setIsPushAddButton(false);
    };
  }, [dispatch]);

  const changeWorktypeId = useCallback(
    (target: string) => {
      // 空文字の場合はundefinedをdispatchする
      if (target === "") {
        dispatch(changeWorktype({ worktypeId: undefined }));
      } else if (!Number.isNaN(Number(target))) {
        dispatch(changeWorktype({ worktypeId: Number(target) }));
      }
    },
    [dispatch]
  );

  const changeTemplateId = useCallback(
    (target: string) => {
      // 空文字の場合はundefinedをdispatchする
      if (target === "") {
        dispatch(changeTemplate({ templateId: undefined }));
      } else if (!Number.isNaN(Number(target))) {
        dispatch(changeTemplate({ templateId: Number(target) }));
      }
    },
    [dispatch]
  );

  const changeAuthorId = useCallback(
    (target: string) => {
      if (!Number.isNaN(target)) {
        dispatch(changeAuthor({ authorId: Number(target) }));
      }
    },
    [dispatch]
  );

  // 追加ボタン押下時の処理
  const handleAdd = useCallback(async () => {
    setIsPushAddButton(true);
    // エラーチェック
    if (hasAuthorIdEmptyError || hasSelectedWorkflowAssineeEmptyError) {
      return;
    }
    const { meta } = await dispatch(createWorkflowAsync());
    if (meta.requestStatus === "fulfilled") {
      onClose();
      dispatch(listWorkflowAsync());
    }
  }, [
    dispatch,
    hasAuthorIdEmptyError,
    hasSelectedWorkflowAssineeEmptyError,
    onClose,
  ]);

  return (
    <div className={`${styles.modal} ${styles.isShow}`}>
      <div className={styles.modalBox}>
        <p className={styles.modalTitle}>
          {t(getTranslationID("workflowPage.label.addRoutingRule"))}
          {/* 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={onClose}
          />
        </p>
        <form className={styles.form}>
          <dl className={`${styles.formList} ${styles.hasbg}`}>
            <dt className={styles.formTitle} />
            <dt>{t(getTranslationID("workflowPage.label.authorID"))}</dt>
            <dd>
              <select
                className={styles.formInput}
                onChange={(e) => {
                  changeAuthorId(e.target.value);
                }}
              >
                <option value="" hidden>
                  {`-- ${t(
                    getTranslationID("workflowPage.label.selectAuthor")
                  )} --`}
                </option>
                {workflowRelations?.authors.map((author) => (
                  <option key={author.authorId} value={author.id}>
                    {author.authorId}
                  </option>
                ))}
              </select>
              {isPushAddButton && hasAuthorIdEmptyError && (
                <span className={styles.formError}>
                  {t(getTranslationID("workflowPage.message.inputEmptyError"))}
                </span>
              )}
            </dd>
            <dt className={styles.overLine}>
              {t(getTranslationID("workflowPage.label.worktypeOptional"))}
            </dt>
            <dd>
              <select
                className={styles.formInput}
                onChange={(e) => {
                  changeWorktypeId(e.target.value);
                }}
              >
                <option value="" hidden>
                  {`-- ${t(
                    getTranslationID("workflowPage.label.selectWorktypeId")
                  )} --`}
                </option>
                <option value="">
                  {`-- ${t(getTranslationID("common.label.notSelected"))} --`}
                </option>
                {workflowRelations?.worktypes.map((worktype) => (
                  <option key={worktype.id} value={worktype.id}>
                    {worktype.worktypeId}
                  </option>
                ))}
              </select>
            </dd>
            <dt className={styles.formTitle}>
              {t(getTranslationID("typistGroupSetting.label.transcriptionist"))}
            </dt>
            <dd className={`${styles.formChange} ${styles.last}`}>
              <ul className={styles.chooseMember}>
                <li className={styles.changeTitle}>
                  {t(getTranslationID("workflowPage.label.selected"))}
                </li>
                {selectedAssignees?.map((x) => {
                  const key = `${x.typistName}_${
                    x.typistUserId ?? x.typistGroupId
                  }`;
                  return (
                    <li key={key}>
                      <input
                        type="checkbox"
                        className={styles.formCheck}
                        value={x.typistName}
                        id={key}
                        checked
                        onClick={() => {
                          dispatch(removeAssignee({ assignee: x }));
                        }}
                      />
                      <label htmlFor={key} title="Remove">
                        {x.typistName}
                      </label>
                    </li>
                  );
                })}
              </ul>
              <p />
              <ul className={styles.holdMember}>
                <li className={styles.changeTitle}>
                  {t(getTranslationID("workflowPage.label.pool"))}
                </li>
                {poolAssignees?.map((x) => {
                  const key = `${x.typistName}_${
                    x.typistUserId ?? x.typistGroupId
                  }`;
                  return (
                    <li key={key}>
                      <input
                        type="checkbox"
                        className={styles.formCheck}
                        value={x.typistName}
                        id={key}
                        onClick={() => dispatch(addAssignee({ assignee: x }))}
                      />
                      <label htmlFor={key} title="Add">
                        {x.typistName}
                      </label>
                    </li>
                  );
                })}
              </ul>
              {isPushAddButton && hasSelectedWorkflowAssineeEmptyError && (
                <span
                  className={styles.formError}
                  style={{ margin: "0px 30px 0px 30px" }}
                >
                  {t(
                    getTranslationID(
                      "workflowPage.message.selectedTypistEmptyError"
                    )
                  )}
                </span>
              )}
            </dd>
            <dt className={styles.overLine}>
              {t(getTranslationID("workflowPage.label.templateOptional"))}
            </dt>
            <dd className={styles.last}>
              <select
                className={styles.formInput}
                onChange={(e) => {
                  changeTemplateId(e.target.value);
                }}
              >
                <option value="" hidden>
                  {`-- ${t(
                    getTranslationID("workflowPage.label.selectTemplate")
                  )} --`}
                </option>
                <option value="">
                  {`-- ${t(getTranslationID("common.label.notSelected"))} --`}
                </option>
                {workflowRelations?.templates.map((template) => (
                  <option
                    key={`${template.name}_${template.id}`}
                    value={template.id}
                  >
                    {template.name}
                  </option>
                ))}
              </select>
            </dd>
            <dd className={`${styles.full} ${styles.alignCenter}`}>
              <input
                type="button"
                value={t(getTranslationID("common.label.save"))}
                className={`${styles.formSubmit} ${styles.marginBtm1} ${
                  !isLoading ? styles.isActive : ""
                }`}
                onClick={handleAdd}
              />
              {isLoading && (
                <img
                  src={progress_activit}
                  className={styles.icLoading}
                  alt="Loading"
                />
              )}
            </dd>
          </dl>
        </form>
      </div>
    </div>
  );
};
