import { AppDispatch } from "app/store";
import React, { useState, useCallback, useEffect } from "react";
import styles from "styles/app.module.scss";
import { useDispatch, useSelector } from "react-redux";
import { getTranslationID } from "translation";
import { useTranslation } from "react-i18next";
import {
  selectAdminName,
  selectCompany,
  selectCountry,
  selectEmail,
  selectInputValidationErrors,
  selectIsLoading,
} from "features/partner/selectors";
import {
  changeAdminName,
  changeCompany,
  changeCountry,
  changeEmail,
  cleanupAddPartner,
} from "features/partner/partnerSlice";
import { createPartnerAccountAsync } from "features/partner";
import close from "../../assets/images/close.svg";
import progress_activit from "../../assets/images/progress_activit.svg";
import { COUNTRY_LIST } from "../SignupPage/constants";

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

export const AddPartnerAccountPopup: React.FC<AddPartnerAccountPopup> = (
  props
) => {
  const { isOpen, onClose } = props;
  const dispatch: AppDispatch = useDispatch();
  const { t } = useTranslation();
  const {
    hasErrorEmptyCompany,
    hasErrorEmptyCountry,
    hasErrorEmptyAdminName,
    hasErrorEmptyEmail,
    hasErrorIncorrectEmail,
  } = useSelector(selectInputValidationErrors);

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

  const companyName = useSelector(selectCompany);
  const country = useSelector(selectCountry);
  const adminName = useSelector(selectAdminName);
  const email = useSelector(selectEmail);
  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);
    };
  });

  const closePopup = useCallback(() => {
    if (isLoading) {
      return;
    }
    setIsPushCreateButton(false);
    dispatch(cleanupAddPartner());
    onClose();
  }, [isLoading, onClose, dispatch]);

  const onAddPartner = useCallback(async () => {
    setIsPushCreateButton(true);
    if (
      hasErrorEmptyCompany ||
      hasErrorEmptyCountry ||
      hasErrorEmptyAdminName ||
      hasErrorEmptyEmail ||
      hasErrorIncorrectEmail
    ) {
      return;
    }

    const { meta } = await dispatch(
      createPartnerAccountAsync({
        companyName,
        country,
        adminName,
        email,
      })
    );
    setIsPushCreateButton(false);

    if (meta.requestStatus === "fulfilled") {
      closePopup();
    }
  }, [
    dispatch,
    closePopup,
    hasErrorEmptyCompany,
    hasErrorEmptyCountry,
    hasErrorEmptyAdminName,
    hasErrorEmptyEmail,
    hasErrorIncorrectEmail,
    companyName,
    country,
    adminName,
    email,
  ]);

  return (
    <div className={`${styles.modal} ${isOpen ? styles.isShow : ""}`}>
      <div className={styles.modalBox}>
        <p className={styles.modalTitle}>
          {t(getTranslationID("addPartnerAccountPopupPage.text.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} ${styles.marginBtm0}`}>
              {t(
                getTranslationID(
                  "addPartnerAccountPopupPage.text.accountInfoTitle"
                )
              )}
            </dt>
            <dt>
              {t(getTranslationID("addPartnerAccountPopupPage.label.company"))}
            </dt>
            <dd>
              <input
                type="text"
                size={64}
                className={`${styles.formInput} ${
                  isPushCreateButton && hasErrorEmptyCompany && styles.isError
                }`}
                onChange={(e) => {
                  dispatch(changeCompany({ company: e.target.value }));
                }}
                value={companyName}
              />
              {isPushCreateButton && hasErrorEmptyCompany && (
                <span className={styles.formError}>
                  {t(
                    getTranslationID(
                      "addPartnerAccountPopupPage.message.inputEmptyError"
                    )
                  )}
                </span>
              )}
            </dd>
            <dt>
              {t(getTranslationID("addPartnerAccountPopupPage.label.country"))}
            </dt>
            <dd>
              <select
                className={`${styles.formInput} ${
                  isPushCreateButton && hasErrorEmptyCountry && styles.isError
                }`}
                onChange={(event) => {
                  dispatch(changeCountry({ country: event.target.value }));
                }}
                value={
                  COUNTRY_LIST.find((x) => x.value === country)?.value ?? ""
                }
              >
                {COUNTRY_LIST.map((x) => (
                  <option key={x.value} value={x.value}>
                    {x.label}
                  </option>
                ))}
              </select>
              {isPushCreateButton && hasErrorEmptyCountry && (
                <span className={styles.formError}>
                  {t(
                    getTranslationID(
                      "addPartnerAccountPopupPage.message.inputEmptyError"
                    )
                  )}
                </span>
              )}
            </dd>
            <dt className={`  ${styles.formTitle} ${styles.marginBtm0}`}>
              {t(
                getTranslationID(
                  "addPartnerAccountPopupPage.text.adminInfoTitle"
                )
              )}
            </dt>
            <dt>
              {t(
                getTranslationID("addPartnerAccountPopupPage.label.adminName")
              )}
            </dt>
            <dd>
              <input
                type="text"
                size={256}
                className={`${styles.formInput} ${
                  isPushCreateButton && hasErrorEmptyAdminName && styles.isError
                }`}
                onChange={(e) => {
                  dispatch(changeAdminName({ adminName: e.target.value }));
                }}
                value={adminName}
              />
              {isPushCreateButton && hasErrorEmptyAdminName && (
                <span className={styles.formError}>
                  {t(
                    getTranslationID(
                      "addPartnerAccountPopupPage.message.inputEmptyError"
                    )
                  )}
                </span>
              )}
            </dd>
            <dt>
              {t(getTranslationID("addPartnerAccountPopupPage.label.email"))}
            </dt>
            <dd>
              <input
                type="text"
                size={64}
                className={`${styles.formInput}
                    ${
                      isPushCreateButton &&
                      (hasErrorEmptyEmail || hasErrorIncorrectEmail) &&
                      styles.isError
                    }`}
                onChange={(e) => {
                  dispatch(changeEmail({ email: e.target.value }));
                }}
                value={email}
              />
              {isPushCreateButton && hasErrorEmptyEmail && (
                <span className={styles.formError}>
                  {t(
                    getTranslationID(
                      "addPartnerAccountPopupPage.message.inputEmptyError"
                    )
                  )}
                </span>
              )}
              {isPushCreateButton && hasErrorIncorrectEmail && (
                <span className={styles.formError}>
                  {t(
                    getTranslationID(
                      "addPartnerAccountPopupPage.message.emailIncorrectError"
                    )
                  )}
                </span>
              )}
            </dd>
            <dd className={`${styles.full} ${styles.alignCenter}`}>
              <input
                type="button"
                name="submit"
                value={t(
                  getTranslationID(
                    "addPartnerAccountPopupPage.label.createAccountButton"
                  )
                )}
                className={`${styles.formSubmit} ${styles.marginBtm1} ${
                  !isLoading ? styles.isActive : ""
                }`}
                onClick={onAddPartner}
              />
              <img
                style={{ display: isLoading ? "inline" : "none" }}
                src={progress_activit}
                className={styles.icLoading}
                alt="Loading"
              />
            </dd>
          </dl>
        </form>
      </div>
    </div>
  );
};
