import React, { useCallback, useEffect, useState } from "react";
import styles from "styles/app.module.scss";
import { useDispatch, useSelector } from "react-redux";
import { Typist } from "api";
import { AppDispatch } from "app/store";
import { getTranslationID } from "translation";
import { useTranslation } from "react-i18next";
import {
  addSelectedTypist,
  cleanupTypistGroup,
  removeSelectedTypist,
  selectPoolTypists,
  selectSelectedTypists,
  selectGroupName,
  changeGroupName,
  selectAddGroupErrors,
} from "features/workflow/typistGroup";
import {
  getTypistGroupAsync,
  listTypistGroupsAsync,
  updateTypistGroupAsync,
} from "features/workflow/typistGroup/operations";
import { openSnackbar } from "features/ui";
import close from "../../assets/images/close.svg";

interface EditTypistGroupPopupProps {
  onClose: (isChanged: boolean) => void;
  isOpen: boolean;
  typistGroupId: number;
}

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

  const [isPushEditButton, setIsPushEditButton] = useState<boolean>(false);

  const poolTypists = useSelector(selectPoolTypists);
  const selectedTypists = useSelector(selectSelectedTypists);
  const groupName = useSelector(selectGroupName);

  const { hasErrorEmptyGroupName, hasErrorSelectedTypistsEmpty } =
    useSelector(selectAddGroupErrors);

  // 表示時のみ実行
  useEffect(() => {
    if (isOpen) {
      dispatch(getTypistGroupAsync({ typistGroupId }));
    }
  }, [dispatch, isOpen, typistGroupId]);

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

  // グループ更新を実行
  const editTypistGroup = useCallback(async () => {
    setIsPushEditButton(true);
    // 入力チェック
    if (hasErrorEmptyGroupName || hasErrorSelectedTypistsEmpty) {
      if (hasErrorSelectedTypistsEmpty) {
        dispatch(
          openSnackbar({
            level: "error",
            message: t(
              getTranslationID(
                "typistGroupSetting.message.selectedTypistEmptyError"
              )
            ),
          })
        );
      }
      return;
    }

    // グループ追加APIを実行
    const { meta } = await dispatch(updateTypistGroupAsync());
    setIsPushEditButton(false);
    if (meta.requestStatus === "fulfilled") {
      closePopup();
      dispatch(listTypistGroupsAsync());
      dispatch(cleanupTypistGroup());
    }
  }, [
    t,
    closePopup,
    dispatch,
    hasErrorEmptyGroupName,
    hasErrorSelectedTypistsEmpty,
  ]);

  return (
    <div className={`${styles.modal} ${isOpen ? styles.isShow : ""}`}>
      <div className={styles.modalBox}>
        <p className={styles.modalTitle}>
          {t(getTranslationID("typistGroupSetting.label.editTypistGroup"))}
          <button type="button" onClick={closePopup}>
            <img src={close} className={styles.modalTitleIcon} alt="close" />
          </button>
        </p>
        <form className={styles.form}>
          <dl className={`${styles.formList} ${styles.hasbg}`}>
            <dt className={styles.formTitle} />
            <dt>{t(getTranslationID("typistGroupSetting.label.groupName"))}</dt>
            <dd>
              <input
                type="text"
                size={40}
                maxLength={50}
                className={styles.formInput}
                value={groupName}
                onChange={(e) =>
                  dispatch(changeGroupName({ groupName: e.target.value }))
                }
              />
              {isPushEditButton && hasErrorEmptyGroupName && (
                <span className={styles.formError}>
                  {t(getTranslationID("common.message.inputEmptyError"))}
                </span>
              )}
            </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("typistGroupSetting.label.selected"))}
                </li>
                {selectedTypists.map((typist: Typist) => (
                  <li key={typist.id}>
                    <input
                      type="checkbox"
                      className={styles.formCheck}
                      value={typist.name}
                      id={`${typist.id}`}
                      checked
                      onClick={() => dispatch(removeSelectedTypist({ typist }))}
                    />
                    <label
                      htmlFor={`${typist.id}`}
                      title={t(
                        getTranslationID("typistGroupSetting.label.remove")
                      )}
                    >
                      {typist.name}
                    </label>
                  </li>
                ))}
              </ul>
              <p />
              <ul className={styles.holdMember}>
                <li className={styles.changeTitle}>
                  {t(getTranslationID("typistGroupSetting.label.pool"))}
                </li>
                {poolTypists.map((typist: Typist) => (
                  <li key={typist.id}>
                    <input
                      type="checkbox"
                      className={styles.formCheck}
                      value={typist.name}
                      id={`${typist.id}`}
                      onClick={() => dispatch(addSelectedTypist({ typist }))}
                    />
                    <label
                      htmlFor={`${typist.id}`}
                      title={t(
                        getTranslationID("typistGroupSetting.label.add")
                      )}
                    >
                      {typist.name}
                    </label>
                  </li>
                ))}
              </ul>
            </dd>
            <dd className={`${styles.full} ${styles.alignCenter}`}>
              <input
                type="button"
                name="submit"
                value={t(getTranslationID("common.label.save"))}
                className={`${styles.formSubmit} ${styles.marginBtm1} ${styles.isActive}`}
                onClick={editTypistGroup}
              />
            </dd>
          </dl>
        </form>
      </div>
    </div>
  );
};
