import React, { useCallback } from "react";
import styles from "styles/app.module.scss";
import { useDispatch, useSelector } from "react-redux";
import {
  changeAssignee,
  selectIsLoading,
  selectPoolTranscriptionists,
  selectSelectedTask,
  selectSelectedTranscriptionists,
  updateAssigneeAsync,
} from "features/dictation";
import { Assignee } from "api";
import { AppDispatch } from "app/store";
import { getTranslationID } from "translation";
import { useTranslation } from "react-i18next";
import close from "../../assets/images/close.svg";
import progress_activit from "../../assets/images/progress_activit.svg";

interface ChangeTranscriptionistPopupProps {
  onClose: (isChanged: boolean) => void;
  isOpen: boolean;
}

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

  const isLoading = useSelector(selectIsLoading);

  // ポップアップを閉じる処理
  const closePopup = useCallback(() => {
    onClose(false);
  }, [onClose]);

  const selectedTask = useSelector(selectSelectedTask);
  const selectedTranscriptionists = useSelector(
    selectSelectedTranscriptionists
  );
  const poolTranscriptionists = useSelector(selectPoolTranscriptionists);

  const removeAssignee = useCallback(
    (assignee: Assignee) => {
      dispatch(
        changeAssignee({
          selected: selectedTranscriptionists.filter(
            (x) =>
              x.typistGroupId !== assignee.typistGroupId ||
              x.typistUserId !== assignee.typistUserId
          ),
        })
      );
    },
    [dispatch, selectedTranscriptionists]
  );

  const addAssignee = useCallback(
    (assignee: Assignee) => {
      dispatch(
        changeAssignee({ selected: [...selectedTranscriptionists, assignee] })
      );
    },
    [dispatch, selectedTranscriptionists]
  );

  const onChangeTranscriptionist = useCallback(async () => {
    // ダイアログ確認
    if (
      !selectedTask ||
      /* eslint-disable-next-line no-alert */
      !window.confirm(t(getTranslationID("common.message.dialogConfirm")))
    ) {
      return;
    }
    const { meta } = await dispatch(
      updateAssigneeAsync({
        audioFileId: selectedTask.audioFileId,
        assignees: selectedTranscriptionists,
      })
    );

    if (meta.requestStatus === "fulfilled") {
      onClose(true);
    }
  }, [dispatch, selectedTranscriptionists, selectedTask, onClose, t]);

  return (
    <div className={`${styles.modal} ${isOpen ? styles.isShow : ""}`}>
      <div className={styles.modalBox}>
        <p className={styles.modalTitle}>
          {t(getTranslationID("dictationPage.label.changeTranscriptionist"))}
          {/* 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 action="" name="" method="" className={styles.form}>
          <dl className={`${styles.formList} ${styles.hasbg}`}>
            <dt className={styles.formTitle} />
            <dt>{t(getTranslationID("dictationPage.label.jobNumber"))}</dt>
            <dd>
              <input
                type="text"
                size={40}
                value={selectedTask?.jobNumber ?? ""}
                className={styles.formInput}
                readOnly
              />
            </dd>
            <dt>{t(getTranslationID("dictationPage.label.authorId"))}</dt>
            <dd>
              <input
                type="text"
                size={40}
                value={selectedTask?.authorId ?? ""}
                className={styles.formInput}
                readOnly
              />
            </dd>
            <dt>{t(getTranslationID("dictationPage.label.workType"))}</dt>
            <dd>
              <input
                type="text"
                size={40}
                value={selectedTask?.workType ?? ""}
                className={styles.formInput}
                readOnly
              />
            </dd>
            <dt className={styles.formTitle}>Transcriptionist</dt>
            <dd className={`${styles.formChange} ${styles.last}`}>
              <ul className={styles.chooseMember}>
                <li className={styles.changeTitle}>
                  {t(
                    getTranslationID(
                      "dictationPage.label.selectedTranscriptionist"
                    )
                  )}
                </li>
                {selectedTranscriptionists?.map((x) => (
                  <li key={`${x.typistGroupId ?? 0}_${x.typistUserId ?? 0}`}>
                    <input
                      type="checkbox"
                      className={styles.formCheck}
                      value={x.typistName}
                      id={x.typistName}
                      checked
                      onClick={() => removeAssignee(x)}
                    />
                    <label htmlFor={x.typistName} title="Remove">
                      {x.typistName}
                    </label>
                  </li>
                ))}
              </ul>
              <p />
              <ul className={styles.holdMember}>
                <li className={styles.changeTitle}>
                  {t(
                    getTranslationID("dictationPage.label.poolTranscriptionist")
                  )}
                </li>
                {poolTranscriptionists?.map((x) => (
                  <li key={`${x.typistGroupId ?? 0}_${x.typistUserId ?? 0}`}>
                    <input
                      type="checkbox"
                      className={styles.formCheck}
                      value={x.typistName}
                      id={x.typistName}
                      onClick={() => addAssignee(x)}
                    />
                    <label htmlFor={x.typistName} title="Add">
                      {x.typistName}
                    </label>
                  </li>
                ))}
              </ul>
            </dd>
            <dd className={`${styles.full} ${styles.alignCenter}`}>
              <input
                type="button"
                name="submit"
                value={t(getTranslationID("dictationPage.label.saveChanges"))}
                className={`${styles.formSubmit} ${styles.marginBtm1} ${
                  !isLoading ? styles.isActive : ""
                }`}
                onClick={onChangeTranscriptionist}
              />
              <img
                style={{ display: isLoading ? "inline" : "none" }}
                src={progress_activit}
                className={styles.icLoading}
                alt="Loading"
              />
            </dd>
          </dl>
        </form>
      </div>
    </div>
  );
};
