import { AppDispatch } from "app/store";
import React, { useCallback, useEffect, useState } from "react";
import styles from "styles/app.module.scss";
import { useDispatch, useSelector } from "react-redux";
import { useTranslation } from "react-i18next";
import {
  selectLicenseAllocateUserId,
  selectLicenseAllocateUserEmail,
  selectLicenseAllocateUserName,
  selectLicenseAllocateUserAuthorId,
  selectLicenseAllocateUserStatus,
  selectLicenseAllocateUserExpirationDate,
  selectAllocatableLicenses,
  getAllocatableLicensesAsync,
  changeSelectedlicenseId,
  selectSelectedlicenseId,
  selectIsLoading,
  listUsersAsync,
  allocateLicenseAsync,
  cleanupLicenseAllocateInfo,
  selectInputValidationErrorsForLicenseAcclocation,
  LICENSE_ALLOCATE_STATUS,
} from "features/user";
import { getTranslationID } from "translation";
import close from "../../assets/images/close.svg";
import progress_activit from "../../assets/images/progress_activit.svg";

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

export const AllocateLicensePopup: React.FC<AllocateLicensePopupProps> = (
  props
) => {
  const { isOpen, onClose } = props;
  const dispatch: AppDispatch = useDispatch();
  const { t } = useTranslation();

  const { hasErrorEmptyLicense } = useSelector(
    selectInputValidationErrorsForLicenseAcclocation
  );

  const id = useSelector(selectLicenseAllocateUserId);
  const email = useSelector(selectLicenseAllocateUserEmail);
  const name = useSelector(selectLicenseAllocateUserName);
  const authorId = useSelector(selectLicenseAllocateUserAuthorId);
  const status = useSelector(selectLicenseAllocateUserStatus);
  const expirationDate = useSelector(selectLicenseAllocateUserExpirationDate);
  const allocatableLicenses = useSelector(selectAllocatableLicenses);
  const selectedlicenseId = useSelector(selectSelectedlicenseId);

  const [isPushAllocateButton, setIsPushAllocateButton] =
    useState<boolean>(false);

  const isLoading = useSelector(selectIsLoading);

  useEffect(() => {
    if (isOpen) {
      // 画面起動時、有効なライセンスを取得する
      dispatch(getAllocatableLicensesAsync());
    }
  }, [isOpen, dispatch]);

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

  const onAllocateLicense = useCallback(async () => {
    setIsPushAllocateButton(true);

    // 入力不正時は何もしない
    if (hasErrorEmptyLicense) {
      return;
    }

    const { meta } = await dispatch(
      allocateLicenseAsync({ userId: id, newLicenseId: selectedlicenseId })
    );
    setIsPushAllocateButton(false);

    if (meta.requestStatus === "fulfilled") {
      closePopup();
      dispatch(listUsersAsync());
    }
  }, [dispatch, closePopup, id, selectedlicenseId, hasErrorEmptyLicense]);

  return (
    <div className={`${styles.modal} ${isOpen ? styles.isShow : ""}`}>
      <div className={styles.modalBox}>
        <p className={styles.modalTitle}>
          {t(getTranslationID("allocateLicensePopupPage.label.title"))}
          <button type="button" onClick={closePopup}>
            <img src={close} className={styles.modalTitleIcon} alt="close" />
          </button>
        </p>
        <form action="" name="" method="" className={styles.form}>
          <dl className={`${styles.formList} ${styles.hasbg}`}>
            <dt className={styles.formTitle}>
              {t(
                getTranslationID(
                  "allocateLicensePopupPage.label.personalInformation"
                )
              )}
            </dt>
            <dt>
              {t(getTranslationID("allocateLicensePopupPage.label.email"))}
            </dt>
            <dd>
              <input
                type="text"
                size={40}
                name=""
                value={email}
                className={styles.formInput}
                readOnly
              />
            </dd>
            <dt>
              {t(getTranslationID("allocateLicensePopupPage.label.name"))}
            </dt>
            <dd>
              <input
                type="text"
                size={40}
                name=""
                value={name}
                className={styles.formInput}
                readOnly
              />
            </dd>
            <dt>
              {t(getTranslationID("allocateLicensePopupPage.label.authorID"))}
            </dt>
            <dd>
              <input
                type="text"
                size={40}
                name=""
                value={authorId}
                className={styles.formInput}
                readOnly
              />
            </dd>
            <dt>
              {t(getTranslationID("allocateLicensePopupPage.label.status"))}
            </dt>
            <dd>
              <input
                type="text"
                size={40}
                name=""
                value={(() => {
                  switch (status) {
                    case LICENSE_ALLOCATE_STATUS.ALLOCATED:
                      return t(
                        getTranslationID(
                          "allocateLicensePopupPage.label.allocated"
                        )
                      );
                    case LICENSE_ALLOCATE_STATUS.NOTALLOCATED:
                      return t(
                        getTranslationID(
                          "allocateLicensePopupPage.label.notAllocated"
                        )
                      );
                    default:
                      return status;
                  }
                })()}
                className={styles.formInput}
                readOnly
              />
            </dd>
            <dt>
              {t(
                getTranslationID(
                  "allocateLicensePopupPage.label.expirationDate"
                )
              )}
            </dt>
            <dd>
              <input
                type="text"
                size={40}
                name=""
                value={expirationDate}
                className={styles.formInput}
                readOnly
              />
            </dd>
            <dt className={styles.formTitle}>
              {t(
                getTranslationID(
                  "allocateLicensePopupPage.label.licenseInformation"
                )
              )}
            </dt>
            <dt>
              {t(
                getTranslationID(
                  "allocateLicensePopupPage.label.licenseAvailable"
                )
              )}
            </dt>
            <dd>
              <select
                name=""
                className={`${styles.formInput} ${
                  isPushAllocateButton && hasErrorEmptyLicense && styles.isError
                }`}
                onChange={(event) => {
                  dispatch(
                    changeSelectedlicenseId({
                      selectedlicenseId: parseInt(event.target.value, 10),
                    })
                  );
                }}
                value={selectedlicenseId ?? ""}
              >
                <option value="">
                  {t(
                    getTranslationID(
                      "allocateLicensePopupPage.label.dropDownHeading"
                    )
                  )}
                </option>
                {allocatableLicenses.map((x) => (
                  <option key={x.licenseId} value={x.licenseId}>
                    {/* one yearの場合はそれに相当する内容、それ以外の場合は値をそのまま表示 */}
                    {x.expiryDate
                      ? x.expiryDate
                      : t(
                          getTranslationID(
                            "allocateLicensePopupPage.label.oneYear"
                          )
                        )}
                  </option>
                ))}
              </select>
              {isPushAllocateButton && hasErrorEmptyLicense && (
                <span className={styles.formError}>
                  {t(
                    getTranslationID(
                      "allocateLicensePopupPage.message.inputEmptyError"
                    )
                  )}
                </span>
              )}
            </dd>
            <dd className={`${styles.full} ${styles.alignCenter}`}>
              <input
                type="button"
                name="submit"
                value={t(
                  getTranslationID(
                    "allocateLicensePopupPage.label.allocateLicense"
                  )
                )}
                className={`${styles.formSubmit} ${styles.marginBtm1} ${styles.isActive}`}
                onClick={onAllocateLicense}
              />
              <img
                style={{ display: isLoading ? "inline" : "none" }}
                src={progress_activit}
                className={styles.icLoading}
                alt="Loading"
              />
            </dd>
          </dl>
        </form>
      </div>
    </div>
  );
};
