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,
  listTypistsAsync,
  removeSelectedTypist,
  selectPoolTypists,
  selectSelectedTypists,
  selectGroupName,
  changeGroupName,
  selectAddGroupErrors,
  cleanupTypistGroup,
} from "features/workflow/typistGroup";
import {
  createTypistGroupAsync,
  listTypistGroupsAsync,
} from "features/workflow/typistGroup/operations";
import { openSnackbar } from "features/ui";
import close from "../../assets/images/close.svg";

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

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

  const [isPushAddButton, setIsPushAddButton] = useState<boolean>(false);

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

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

  // 開閉時のみ実行
  useEffect(() => {
    if (isOpen) {
      dispatch(listTypistsAsync());
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isOpen]);

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

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

    // グループ追加APIを実行
    const { meta } = await dispatch(
      createTypistGroupAsync({
        typistGroupName: groupName,
        typistIds: selectedTypists.map((typist) => typist.id),
      })
    );
    setIsPushAddButton(false);
    if (meta.requestStatus === "fulfilled") {
      closePopup();
      dispatch(listTypistGroupsAsync());
    }
  }, [
    t,
    closePopup,
    dispatch,
    groupName,
    selectedTypists,
    hasErrorEmptyGroupName,
    hasErrorSelectedTypistsEmpty,
  ]);

  return (
    <div className={`${styles.modal} ${isOpen ? styles.isShow : ""}`}>
      <div className={styles.modalBox}>
        <p className={styles.modalTitle}>
          {t(getTranslationID("typistGroupSetting.label.addTypistGroup"))}
          <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 }))
                }
              />
              {isPushAddButton && 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={addTypistGroup}
              />
            </dd>
          </dl>
        </form>
      </div>
    </div>
  );
};
