import React, { useState, useCallback, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { AppDispatch } from "app/store";
import { useDispatch, useSelector } from "react-redux";
import styles from "../../styles/app.module.scss";
import { getTranslationID } from "../../translation";
import close from "../../assets/images/close.svg";
import {
  changeNumberOfCreateLicenses,
  selectNumberOfCreateLicenses,
  selectInputValidationErrors,
  createCardLicenseAsync,
  cleanupApps,
  selectIsLoading,
} from "../../features/license/licenseCardIssue/index";
import progress_activit from "../../assets/images/progress_activit.svg";

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

export const CardLicenseIssuePopup: React.FC<CardLicenseIssuePopupProps> = (
  props
) => {
  const { onClose } = props;
  const { t } = useTranslation();
  const dispatch: AppDispatch = useDispatch();
  const initCount = useSelector(selectNumberOfCreateLicenses);
  const [count, setCount] = useState<number>(initCount);
  const isLoading = useSelector(selectIsLoading);

  // ブラウザのウィンドウが閉じられようとしている場合に発火するイベントハンドラ
  const handleBeforeUnload = (e: BeforeUnloadEvent) => {
    // isLoadingがtrueの場合は確認ダイアログを表示する
    if (isLoading) {
      e.preventDefault();
      // ChromeではreturnValueが必要
      e.returnValue = "";
    }
  };

  // コンポーネントがマウントされた時にイベントハンドラを登録する
  useEffect(() => {
    window.addEventListener("beforeunload", handleBeforeUnload);
    // コンポーネントがアンマウントされるときにイベントハンドラを解除する
    return () => {
      window.removeEventListener("beforeunload", handleBeforeUnload);
    };
  });

  useEffect(
    () => () => {
      // useEffectのreturnとしてcleanupAppsを実行することで、ポップアップのアンマウント時に初期化を行う
      dispatch(cleanupApps());
    },
    [dispatch]
  );

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

  // 画面からのパラメータ
  const createCount = useSelector(selectNumberOfCreateLicenses);

  const [isPushCreateButton, setIsPushCreateButton] = useState<boolean>(false);

  // エラー宣言
  const { hasErrorIncorrectNumberOfCreateLicenses } = useSelector(
    selectInputValidationErrors
  );

  // 注文ボタン押下時
  const onCreateLicense = useCallback(async () => {
    setIsPushCreateButton(true);

    // エラーチェックを実施
    if (hasErrorIncorrectNumberOfCreateLicenses) {
      return;
    }

    // 注文APIの呼び出し
    const { meta } = await dispatch(
      createCardLicenseAsync({
        createCount,
      })
    );
    setIsPushCreateButton(false);

    if (meta.requestStatus === "fulfilled") {
      closePopup();
    }
  }, [
    dispatch,
    closePopup,
    hasErrorIncorrectNumberOfCreateLicenses,
    createCount,
  ]);

  // HTML
  return (
    <div className={`${styles.modal} ${styles.isShow}`}>
      <div className={styles.modalBox}>
        <p className={styles.modalTitle}>
          {t(getTranslationID("cardLicenseIssuePopupPage.label.title"))}
          <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}>
              {t(getTranslationID("cardLicenseIssuePopupPage.label.subTitle"))}
            </dt>
            <dt className={styles.overLine}>
              {t(getTranslationID("cardLicenseIssuePopupPage.label.number"))}
            </dt>
            <dd className="">
              <input
                type="number"
                size={40}
                name="numberOfLicense"
                value={count}
                min={1}
                max={9999}
                step={1}
                className={styles.formInput}
                onChange={(e) => {
                  const input = Number(
                    e.target.value.replace(/[-.]/g, "").substring(0, 4)
                  );
                  setCount(input);
                }}
                onBlur={(e) => {
                  dispatch(
                    changeNumberOfCreateLicenses({
                      numberOfCreateLicenses: Number(e.target.value),
                    })
                  );
                }}
              />
              {isPushCreateButton &&
                hasErrorIncorrectNumberOfCreateLicenses && (
                  <span className={styles.formError}>
                    {t(
                      getTranslationID(
                        "cardLicenseIssuePopupPage.message.createNumberIncorrectError"
                      )
                    )}
                  </span>
                )}
            </dd>
            <dd className={`${styles.full} ${styles.alignCenter}`}>
              <input
                type="button"
                name="submit"
                value={t(
                  getTranslationID(
                    "cardLicenseIssuePopupPage.label.createButton"
                  )
                )}
                className={`${styles.formSubmit} ${styles.marginBtm1} ${
                  !isLoading ? styles.isActive : ""
                }`}
                onClick={onCreateLicense}
              />
              <img
                style={{ display: isLoading ? "inline" : "none" }}
                src={progress_activit}
                className={styles.icLoading}
                alt="Loading"
              />
            </dd>
          </dl>
        </form>
      </div>
    </div>
  );
};
