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,
  changeTypistGroupId,
  changeAutoRenew,
  changeLicenseAlert,
  changeNotification,
  cleanupAddUser,
  selectName,
  selectEmail,
  selectRole,
  selectAuthorId,
  selectTypistGroupId,
  selectInputValidationErrors,
  selectAutoRenew,
  selectLicenseAlert,
  selectNtotification,
  addUserAsync,
  selectIsLoading,
} 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 closePopup = useCallback(() => {
    setIsPushCreateButton(false);
    dispatch(cleanupAddUser());
    onClose();
  }, [onClose, dispatch]);

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

  const name = useSelector(selectName);
  const email = useSelector(selectEmail);
  const role = useSelector(selectRole);
  const authorId = useSelector(selectAuthorId);
  const typistGroupId = useSelector(selectTypistGroupId);
  const autoRenew = useSelector(selectAutoRenew);
  const licenseAlert = useSelector(selectLicenseAlert);
  const notification = useSelector(selectNtotification);

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

  const isLoading = useSelector(selectIsLoading);

  const onAddUser = useCallback(async () => {
    setIsPushCreateButton(true);
    if (
      hasErrorEmptyName ||
      hasErrorEmptyEmail ||
      hasErrorEmptyAuthorId ||
      hasErrorIncorrectEmail ||
      hasErrorIncorrectAuthorId
    ) {
      return;
    }
    if (role !== USER_ROLES.AUTHOR) {
      changeAuthorId({ authorId: undefined });
    }
    if (role !== USER_ROLES.TYPIST) {
      changeTypistGroupId({ typistGroupId: undefined });
    }

    const { meta } = await dispatch(
      addUserAsync({
        name,
        email,
        role,
        authorId:
          role === USER_ROLES.AUTHOR ? authorId ?? undefined : undefined,
        typistGroupId: role === USER_ROLES.TYPIST ? typistGroupId : undefined,
        autoRenew,
        licenseAlert,
        notification,
      })
    );
    setIsPushCreateButton(false);

    if (meta.requestStatus === "fulfilled") {
      closePopup();
    }
  }, [
    dispatch,
    closePopup,
    hasErrorEmptyName,
    hasErrorEmptyEmail,
    hasErrorEmptyAuthorId,
    hasErrorIncorrectEmail,
    hasErrorIncorrectAuthorId,
    name,
    email,
    role,
    authorId,
    typistGroupId,
    autoRenew,
    licenseAlert,
    notification,
  ]);

  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={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={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={USER_ROLES.AUTHOR}>
                <input
                  type="radio"
                  name="role"
                  className={styles.formRadio}
                  checked={role === USER_ROLES.AUTHOR}
                  onChange={() => {
                    dispatch(changeRole({ role: USER_ROLES.AUTHOR }));
                  }}
                />
                {t(getTranslationID("userListPage.label.author"))}
              </label>
              <label htmlFor={USER_ROLES.TYPIST}>
                <input
                  type="radio"
                  name="role"
                  className={styles.formRadio}
                  checked={role === USER_ROLES.TYPIST}
                  onChange={() => {
                    dispatch(changeRole({ role: USER_ROLES.TYPIST }));
                  }}
                />
                {t(getTranslationID("userListPage.label.transcriptionist"))}
              </label>
              <label htmlFor={USER_ROLES.NONE}>
                <input
                  type="radio"
                  name="role"
                  className={styles.formRadio}
                  checked={role === USER_ROLES.NONE}
                  onChange={() => {
                    dispatch(changeRole({ role: USER_ROLES.NONE }));
                  }}
                />
                {t(getTranslationID("userListPage.label.none"))}
              </label>
            </dd>
            {/** Author 選択時に表示 */}
            {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={authorId ?? undefined}
                    onChange={(e) => {
                      dispatch(changeAuthorId({ authorId: e.target.value }));
                    }}
                  />
                  {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>
              </div>
            )}

            {/** Transcriptionist 選択時に表示 */}
            {role === USER_ROLES.TYPIST && (
              <div className={styles.slideSet} id="">
                <dt className={`${styles.overLine} ${styles.marginBtm0}`}>
                  {t(getTranslationID("userListPage.label.addToGroup"))}
                </dt>
                <dd>
                  <select
                    className={styles.formInput}
                    onChange={(e) => {
                      dispatch(
                        changeTypistGroupId({
                          typistGroupId: Number(e.target.value),
                        })
                      );
                    }}
                  >
                    {/** XXX: タイピストグループは後ほど差し替える */}
                    <option value={0}>
                      {t(getTranslationID("userListPage.label.selectGroup"))}
                    </option>
                    <option value={1}>Tgroup A</option>
                    <option value={2}>Tgroup B</option>
                    <option value={3}>Tgroup C</option>
                  </select>
                </dd>
              </div>
            )}

            <dt>{t(getTranslationID("userListPage.label.setting"))}</dt>
            <dd className={styles.last}>
              <p>
                <label htmlFor="Auto renew">
                  <input
                    type="checkbox"
                    className={styles.formCheck}
                    checked={autoRenew}
                    onChange={(e) => {
                      dispatch(
                        changeAutoRenew({ autoRenew: e.target.checked })
                      );
                    }}
                  />
                  {t(getTranslationID("userListPage.label.autoRenew"))}
                </label>
              </p>
              <p>
                <label htmlFor="License Alert">
                  <input
                    type="checkbox"
                    checked={licenseAlert}
                    className={styles.formCheck}
                    onChange={(e) => {
                      dispatch(
                        changeLicenseAlert({ licenseAlert: e.target.checked })
                      );
                    }}
                  />
                  {t(getTranslationID("userListPage.label.licenseAlert"))}
                </label>
              </p>
              <p>
                <label htmlFor="Notification">
                  <input
                    type="checkbox"
                    checked={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>
  );
};
