import React, { useCallback, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
  selectInputValidationErrors,
  selectFileDeleteSetting,
  updateFileDeleteSettingAsync,
  selectIsLoading,
  getAccountRelationsAsync,
} from "features/account";
import { AppDispatch } from "app/store";
import { useTranslation } from "react-i18next";
import styles from "../../styles/app.module.scss";
import { getTranslationID } from "../../translation";
import close from "../../assets/images/close.svg";
import {
  changeAutoFileDelete,
  changeFileRetentionDays,
} from "../../features/account/accountSlice";
import progress_activit from "../../assets/images/progress_activit.svg";

interface FileDeleteSettingPopupProps {
  // eslint-disable-next-line react/no-unused-prop-types
  onClose: () => void;
}

export const FileDeleteSettingPopup: React.FC<FileDeleteSettingPopupProps> = (
  props
) => {
  const { onClose } = props;

  const dispatch: AppDispatch = useDispatch();
  const [t] = useTranslation();

  const isLoading = useSelector(selectIsLoading);
  const fileDeleteSetting = useSelector(selectFileDeleteSetting);
  const { hasFileRetentionDaysError } = useSelector(
    selectInputValidationErrors
  );

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

  const [isPushSubmitButton, setIsPushSubmitButton] = useState<boolean>(false);

  const onUpdateFileDeleteSetting = useCallback(async () => {
    if (isLoading) return;
    setIsPushSubmitButton(true);
    if (hasFileRetentionDaysError) {
      return;
    }

    const { meta } = await dispatch(
      updateFileDeleteSettingAsync({
        autoFileDelete: fileDeleteSetting.autoFileDelete,
        fileRetentionDays: fileDeleteSetting.fileRetentionDays,
      })
    );
    setIsPushSubmitButton(false);
    if (meta.requestStatus === "fulfilled") {
      closePopup();
      dispatch(getAccountRelationsAsync());
    }
  }, [
    closePopup,
    dispatch,
    fileDeleteSetting.autoFileDelete,
    fileDeleteSetting.fileRetentionDays,
    hasFileRetentionDaysError,
    isLoading,
  ]);

  return (
    <div className={`${styles.modal} ${styles.isShow}`}>
      <div className={styles.modalBox}>
        <p className={styles.modalTitle}>
          {t(getTranslationID("fileDeleteSettingPopup.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} />
            <dt>
              {t(
                getTranslationID(
                  "fileDeleteSettingPopup.label.autoFileDeleteCheck"
                )
              )}
            </dt>
            <dd className={styles.last}>
              <p>
                {/* eslint-disable-next-line jsx-a11y/label-has-associated-control */}
                <label>
                  <input
                    type="checkbox"
                    className={styles.formCheck}
                    checked={fileDeleteSetting.autoFileDelete}
                    onChange={(e) => {
                      dispatch(
                        changeAutoFileDelete({
                          autoFileDelete: e.target.checked,
                        })
                      );
                    }}
                  />
                </label>
              </p>
              <p className={styles.txWsline}>
                {t(
                  getTranslationID(
                    "fileDeleteSettingPopup.label.daysAnnotation"
                  )
                )}
              </p>
              <input
                type="number"
                min={1}
                max={999}
                value={fileDeleteSetting.fileRetentionDays}
                className={`${styles.formInput} ${styles.short}`}
                disabled={!fileDeleteSetting.autoFileDelete}
                onChange={(e) => {
                  dispatch(
                    changeFileRetentionDays({
                      fileRetentionDays: Number(e.target.value),
                    })
                  );
                }}
              />{" "}
              {t(getTranslationID("fileDeleteSettingPopup.label.days"))}
              {isPushSubmitButton && hasFileRetentionDaysError && (
                <span className={styles.formError}>
                  {t(
                    getTranslationID(
                      "fileDeleteSettingPopup.label.daysValidationError"
                    )
                  )}
                </span>
              )}
            </dd>
            <dd className={`${styles.full} ${styles.alignCenter}`}>
              <input
                type="button"
                name="submit"
                value={t(
                  getTranslationID("fileDeleteSettingPopup.label.saveButton")
                )}
                className={`${styles.formSubmit} ${styles.marginBtm1} ${
                  !isLoading ? styles.isActive : ""
                }`}
                onClick={onUpdateFileDeleteSetting}
                disabled={isLoading}
              />
            </dd>
            <img
              style={{ display: isLoading ? "inline" : "none" }}
              src={progress_activit}
              className={styles.icLoading}
              alt="Loading"
            />
          </dl>
        </form>
      </div>
    </div>
  );
};
