import React, { useCallback, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { AppDispatch } from "app/store";
import { useDispatch, useSelector } from "react-redux";
import {
  issueTrialLicenseAsync,
  cleanupApps,
  selectIsLoading,
  selectNumberOfLicenses,
  selectExpirationDate,
  setExpirationDate,
} from "features/license/licenseTrialIssue";
import styles from "../../styles/app.module.scss";
import { getTranslationID } from "../../translation";
import close from "../../assets/images/close.svg";
import progress_activit from "../../assets/images/progress_activit.svg";
import { SearchPartner, PartnerLicenseInfo } from "../../api";

interface TrialLicenseIssuePopupProps {
  onClose: () => void;
  selectedRow?: PartnerLicenseInfo | SearchPartner;
}

export const TrialLicenseIssuePopup: React.FC<TrialLicenseIssuePopupProps> = (
  props
) => {
  const { onClose, selectedRow } = props;
  const { t } = useTranslation();
  const dispatch: AppDispatch = useDispatch();
  const isLoading = useSelector(selectIsLoading);

  const numberOfLicenses = useSelector(selectNumberOfLicenses);
  const expirationDate = useSelector(selectExpirationDate);

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

  // ポップアップ表示時
  useEffect(() => {
    // トライアルライセンスの有効期限を設定。
    dispatch(setExpirationDate());
  }, [dispatch]);

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

  // 発行ボタン押下時
  const onIssueTrialLicense = useCallback(async () => {
    // トライアルライセンス発行APIの呼び出し
    const { meta } = await dispatch(issueTrialLicenseAsync({ selectedRow }));
    if (meta.requestStatus === "fulfilled") {
      closePopup();
    }
  }, [dispatch, closePopup, selectedRow]);

  // HTML
  return (
    <div className={`${styles.modal} ${styles.isShow}`}>
      <div className={styles.modalBox}>
        <p className={styles.modalTitle}>
          {t(getTranslationID("trialLicenseIssuePopupPage.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("trialLicenseIssuePopupPage.label.subTitle"))}
            </dt>
            <dt className={styles.overLine}>
              {t(
                getTranslationID(
                  "trialLicenseIssuePopupPage.label.numberOfLicenses"
                )
              )}
            </dt>
            <dd>{numberOfLicenses}</dd>
            <dt>
              {t(
                getTranslationID(
                  "trialLicenseIssuePopupPage.label.expirationDate"
                )
              )}
            </dt>
            <dd>{expirationDate}</dd>
            <dd className={`${styles.full} ${styles.alignCenter}`}>
              <input
                type="button"
                name="submit"
                value={t(
                  getTranslationID(
                    "trialLicenseIssuePopupPage.label.issueButton"
                  )
                )}
                className={`${styles.formSubmit} ${styles.marginBtm1} ${
                  !isLoading ? styles.isActive : ""
                }`}
                onClick={onIssueTrialLicense}
              />
              <img
                style={{ display: isLoading ? "inline" : "none" }}
                src={progress_activit}
                className={styles.icLoading}
                alt="Loading"
              />
            </dd>
          </dl>
        </form>
      </div>
    </div>
  );
};
