import { AppDispatch } from "app/store";
import React, { useState, useCallback } 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 {
  changeEmail,
  changeName,
  changeRole,
  changeAuthorId,
  changeAutoRenew,
  changeNotification,
  cleanupAddUser,
  addUserAsync,
  selectAddUser,
  selectInputValidationErrors,
  selectIsLoading,
  changePrompt,
  changeEncryption,
  changeEncryptionPassword,
  listUsersAsync,
} from "features/user";
import { USER_ROLES } from "components/auth/constants";
import close from "../../assets/images/close.svg";
import progress_activit from "../../assets/images/progress_activit.svg";

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

export const UserAddPopup: React.FC<UserAddPopupProps> = (props) => {
  const { isOpen, onClose } = props;
  const dispatch: AppDispatch = useDispatch();
  const { t } = useTranslation();
  const [isPasswordHide, setIsPasswordHide] = useState<boolean>(true);
  // AddUserの情報を取得
  const addUser = useSelector(selectAddUser);

  const closePopup = useCallback(() => {
    setIsPushCreateButton(false);
    dispatch(cleanupAddUser());
    onClose();
  }, [onClose, dispatch]);

  const {
    hasErrorEmptyName,
    hasErrorEmptyEmail,
    hasErrorEmptyAuthorId,
    hasErrorIncorrectEmail,
    hasErrorIncorrectAuthorId,
    hasErrorIncorrectEncryptionPassword,
  } = useSelector(selectInputValidationErrors);

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

  const isLoading = useSelector(selectIsLoading);

  const onAddUser = useCallback(async () => {
    setIsPushCreateButton(true);
    if (
      hasErrorEmptyName ||
      hasErrorEmptyEmail ||
      hasErrorEmptyAuthorId ||
      hasErrorIncorrectEmail ||
      hasErrorIncorrectAuthorId ||
      hasErrorIncorrectEncryptionPassword
    ) {
      return;
    }

    const { meta } = await dispatch(addUserAsync());
    setIsPushCreateButton(false);

    if (meta.requestStatus === "fulfilled") {
      closePopup();
      dispatch(listUsersAsync());
    }
  }, [
    hasErrorEmptyName,
    hasErrorEmptyEmail,
    hasErrorEmptyAuthorId,
    hasErrorIncorrectEmail,
    hasErrorIncorrectAuthorId,
    hasErrorIncorrectEncryptionPassword,
    dispatch,
    closePopup,
  ]);

  return (
    <div className={`${styles.modal} ${isOpen ? styles.isShow : ""}`}>
      <div className={styles.modalBox}>
        <p className={styles.modalTitle}>
          {t(getTranslationID("userListPage.label.addUser"))}
          <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("userListPage.label.personal"))}
            </dt>
            <dt>{t(getTranslationID("userListPage.label.name"))}</dt>
            <dd>
              <input
                type="text"
                size={40}
                maxLength={255}
                className={styles.formInput}
                value={addUser.name}
                onChange={(e) => {
                  dispatch(changeName({ name: e.target.value }));
                }}
              />
              {isPushCreateButton && hasErrorEmptyName && (
                <span className={styles.formError}>
                  {t(getTranslationID("signupPage.message.inputEmptyError"))}
                </span>
              )}
            </dd>
            <dt>{t(getTranslationID("userListPage.label.email"))}</dt>
            <dd>
              <input
                type="email"
                size={40}
                maxLength={255}
                className={styles.formInput}
                value={addUser.email}
                onChange={(e) => {
                  dispatch(changeEmail({ email: e.target.value }));
                }}
              />
              {isPushCreateButton && hasErrorEmptyEmail && (
                <span className={styles.formError}>
                  {t(getTranslationID("signupPage.message.inputEmptyError"))}
                </span>
              )}
              {isPushCreateButton && hasErrorIncorrectEmail && (
                <span className={styles.formError}>
                  {t(
                    getTranslationID("signupPage.message.emailIncorrectError")
                  )}
                </span>
              )}
            </dd>
            <dt>{t(getTranslationID("userListPage.label.role"))}</dt>
            <dd>
              <label htmlFor={`add_${USER_ROLES.AUTHOR}`}>
                <input
                  id={`add_${USER_ROLES.AUTHOR}`}
                  type="radio"
                  name="role"
                  className={styles.formRadio}
                  checked={addUser.role === USER_ROLES.AUTHOR}
                  onChange={() => {
                    dispatch(changeRole({ role: USER_ROLES.AUTHOR }));
                  }}
                />
                {t(getTranslationID("userListPage.label.author"))}
              </label>
              <label htmlFor={`add_${USER_ROLES.TYPIST}`}>
                <input
                  id={`add_${USER_ROLES.TYPIST}`}
                  type="radio"
                  name="role"
                  className={styles.formRadio}
                  checked={addUser.role === USER_ROLES.TYPIST}
                  onChange={() => {
                    dispatch(changeRole({ role: USER_ROLES.TYPIST }));
                  }}
                />
                {t(getTranslationID("userListPage.label.transcriptionist"))}
              </label>
              <label htmlFor={`add_${USER_ROLES.NONE}`}>
                <input
                  id={`add_${USER_ROLES.NONE}`}
                  type="radio"
                  name="role"
                  className={styles.formRadio}
                  checked={addUser.role === USER_ROLES.NONE}
                  onChange={() => {
                    dispatch(changeRole({ role: USER_ROLES.NONE }));
                  }}
                />
                {t(getTranslationID("userListPage.label.none"))}
              </label>
            </dd>
            {/** Author 選択時に表示 */}
            {addUser.role === USER_ROLES.AUTHOR && (
              <div className={styles.slideSet} id="">
                <dt>{t(getTranslationID("userListPage.label.authorID"))}</dt>
                <dd>
                  <input
                    type="text"
                    size={40}
                    maxLength={16}
                    className={styles.formInput}
                    value={addUser.authorId ?? undefined}
                    onChange={(e) => {
                      dispatch(
                        changeAuthorId({
                          authorId: e.target.value.toUpperCase(),
                        })
                      );
                    }}
                  />
                  {isPushCreateButton && hasErrorEmptyAuthorId && (
                    <span className={styles.formError}>
                      {t(
                        getTranslationID("signupPage.message.inputEmptyError")
                      )}
                    </span>
                  )}
                  {isPushCreateButton && hasErrorIncorrectAuthorId && (
                    <span className={styles.formError}>
                      {t(
                        getTranslationID(
                          "userListPage.message.authorIdIncorrectError"
                        )
                      )}
                    </span>
                  )}
                </dd>
                <dt>{t(getTranslationID("userListPage.label.encryption"))}</dt>
                <dd>
                  <label htmlFor="encryption">
                    <input
                      type="checkbox"
                      className={styles.formCheck}
                      checked={addUser.encryption}
                      onChange={(e) => {
                        dispatch(
                          changeEncryption({ encryption: e.target.checked })
                        );
                      }}
                    />
                  </label>
                  {addUser.encryption && (
                    <p className={`${styles.encryptionPass} ${styles.isShow}`}>
                      {t(
                        getTranslationID(
                          "userListPage.label.encryptionPassword"
                        )
                      )}
                      <input
                        type={isPasswordHide ? "password" : "text"}
                        size={40}
                        maxLength={16}
                        className={`${styles.formInput} ${styles.password}`}
                        value={addUser.encryptionPassword ?? undefined}
                        onChange={(e) => {
                          dispatch(
                            changeEncryptionPassword({
                              encryptionPassword: e.target.value,
                            })
                          );
                        }}
                      />
                      <span
                        className={styles.formIconEye}
                        onClick={() => {
                          setIsPasswordHide(!isPasswordHide);
                        }}
                        onKeyDown={() => {
                          setIsPasswordHide(!isPasswordHide);
                        }}
                        role="button"
                        tabIndex={0}
                        aria-label="IconEye"
                      />
                      {isPushCreateButton &&
                        hasErrorIncorrectEncryptionPassword && (
                          <span className={styles.formError}>
                            {t(
                              getTranslationID(
                                "userListPage.message.encryptionPasswordCorrectError"
                              )
                            )}
                          </span>
                        )}
                      <span className={styles.formComment}>
                        {t(
                          getTranslationID(
                            "userListPage.label.encryptionPasswordTerm"
                          )
                        )}
                      </span>
                    </p>
                  )}
                </dd>
                <dt>{t(getTranslationID("userListPage.label.prompt"))}</dt>
                <dd>
                  <label htmlFor="prompt">
                    <input
                      type="checkbox"
                      className={styles.formCheck}
                      checked={addUser.prompt}
                      onChange={(e) => {
                        dispatch(changePrompt({ prompt: e.target.checked }));
                      }}
                    />
                  </label>
                </dd>
              </div>
            )}
            <dt>{t(getTranslationID("userListPage.label.setting"))}</dt>
            <dd className={styles.last}>
              <p>
                <label htmlFor="add_AutoRenew">
                  <input
                    type="checkbox"
                    id="add_AutoRenew"
                    className={styles.formCheck}
                    checked={addUser.autoRenew}
                    onChange={(e) => {
                      dispatch(
                        changeAutoRenew({ autoRenew: e.target.checked })
                      );
                    }}
                  />
                  {t(getTranslationID("userListPage.label.autoRenew"))}
                </label>
              </p>
              <p>
                <label htmlFor="add_Notification">
                  <input
                    type="checkbox"
                    id="add_Notification"
                    checked={addUser.notification}
                    className={styles.formCheck}
                    onChange={(e) => {
                      dispatch(
                        changeNotification({ notification: e.target.checked })
                      );
                    }}
                  />
                  {t(getTranslationID("userListPage.label.notification"))}
                </label>
              </p>
            </dd>
            <dd className={`${styles.full} ${styles.alignCenter}`}>
              <input
                type="button"
                name="submit"
                value="Add user"
                className={`${styles.formSubmit} ${styles.marginBtm1} ${
                  !isLoading ? styles.isActive : ""
                }`}
                onClick={onAddUser}
              />
              <img
                style={{ display: isLoading ? "inline" : "none" }}
                src={progress_activit}
                className={styles.icLoading}
                alt="Loading"
              />
            </dd>
          </dl>
        </form>
      </div>
    </div>
  );
};
