import {createEvent} from "../utils/create-event";
import {appendLoader, hideLoader, showLoader} from "../utils/loader";
import {
  showValidationErrors,
  clearValidationErrors,
  validateGuidPattern,
  validateUserFriendlyIdPattern
} from "../utils/validation";

var Wick = window.Wick || {};

Wick.AddProjectListId = {
  ADD_PROJECT_LIST_EVENT: 'addProjectList',
  HIDDEN_CLASS_NAME: 'd-none',
  el: {
    emptyBasketForm: '.add-list-id__form',
    $searchInput: $('.add-list-id__form #project-id'),
    $btnClear: $('.add-list-id__form .btn--clear'),
    $btnSubmit: $('.btn--add-to-basket'),
    emptyBasketBody: $('.add-list-id__body'),
    basketLoader: '.basket-loader',
    loader: '.add-list-id-loader',
  },
  loaderPayload: {
    wrapper: '.add-list-id',
    hidden: true,
    titleLoader: 'Adding items to your basket',
    modifier: 'add-list-id-loader',
  },
  defaultErrorMessage: 'Something went wrong',
  errorMessage: 'Invalid project list id',
  loaderTextForBasket: 'Adding items to your basket',
  getProjectId () {
    return Wick.AddProjectListId.el.$searchInput.val();
  },
  disabledSubmitBtn () {
    Wick.AddProjectListId.el.$btnSubmit.prop('disabled', Wick.AddProjectListId.getProjectId().length === 0);
  },
  validateProjectListId () {
    return validateGuidPattern(Wick.AddProjectListId.getProjectId()) || validateUserFriendlyIdPattern(Wick.AddProjectListId.getProjectId());
  },
  checkVisibilityOfClearButton () {
    Wick.AddProjectListId.el.$btnClear.toggleClass('d-block', Wick.AddProjectListId.getProjectId().length > 0);
  },
  handleInput () {
    Wick.AddProjectListId.checkVisibilityOfClearButton();
    Wick.AddProjectListId.disabledSubmitBtn();

    if (!Wick.AddProjectListId.getProjectId().length) {
      clearValidationErrors(Wick.AddProjectListId.el.emptyBasketForm);
      Wick.AddProjectListId.checkVisibilityOfClearButton();
    }
  },
  navigateTo(url) {
    window.location.href = url;
  },
  getUpdatedLoader() {
    if ($(Wick.AddProjectListId.el.basketLoader).length) {
      $(`${Wick.AddProjectListId.el.basketLoader} h2`).text(Wick.AddProjectListId.loaderTextForBasket);
      return Wick.AddProjectListId.el.basketLoader;
    }

    return Wick.AddProjectListId.el.loader
  },
  restoreOriginalLoaderText() {
    if ($(Wick.AddProjectListId.el.basketLoader).length) {
      $(`${Wick.AddProjectListId.el.basketLoader} h2`).text(Wick.BasketPage.loaderPayload.titleLoader);
    }
  },
  requestToAddProjectList () {
    const projectIdFromList = Wick.AddProjectListId.getProjectId();
    const activeLoader = Wick.AddProjectListId.getUpdatedLoader();

    showLoader(activeLoader);
    if (!$(Wick.AddProjectListId.el.basketLoader).length) {
      Wick.AddProjectListId.el.emptyBasketBody.hide();
    }

    return new Promise((resolve, reject) => {
      const payload = {
        projectEntryId: projectIdFromList,
      }
      const eventDetail = {resolve, reject};
      const event = createEvent(Wick.AddProjectListId.ADD_PROJECT_LIST_EVENT, payload, eventDetail);
      window.dispatchEvent(event);
    })
      .then(({redirectUrl}) => {
        if (!redirectUrl) {
          return;
        }

        Wick.AddProjectListId.navigateTo(redirectUrl);
      })
      .catch(({errorMessage}) => {
        const currentErrorMessage = errorMessage ? errorMessage : Wick.AddProjectListId.defaultErrorMessage;

        if (!$(Wick.AddProjectListId.el.basketLoader).length) {
          Wick.AddProjectListId.el.emptyBasketBody.show();
        }

        showValidationErrors(Wick.AddProjectListId.el.emptyBasketForm, currentErrorMessage);
      })
      .finally(() => {
        hideLoader(activeLoader);
        Wick.AddProjectListId.restoreOriginalLoaderText();
      })
  },
  handleSubmit () {
    clearValidationErrors(Wick.AddProjectListId.el.emptyBasketForm);

    if (!Wick.AddProjectListId.validateProjectListId()) {
      showValidationErrors(Wick.AddProjectListId.el.emptyBasketForm, Wick.AddProjectListId.errorMessage);
      Wick.AddProjectListId.checkVisibilityOfClearButton();
      return;
    }

    Wick.AddProjectListId.requestToAddProjectList();
  },
  clearSearchInputOnPageLeave() {
    $(window).on('beforeunload', function() {
      Wick.AddProjectListId.el.$searchInput.val('');
      Wick.AddProjectListId.checkVisibilityOfClearButton();
      Wick.AddProjectListId.disabledSubmitBtn();
    });
  },
  addListenersToAddProjectList () {
    Wick.AddProjectListId.el.$searchInput.on('input', Wick.AddProjectListId.handleInput);
    $(Wick.AddProjectListId.el.emptyBasketForm).on('submit', Wick.AddProjectListId.handleSubmit);

    $(document).on('clearInput', function(e, form) {
      if(form.find(Wick.AddProjectListId.el.$btnSubmit).length > 0) {
        clearValidationErrors(Wick.AddProjectListId.el.emptyBasketForm);
        Wick.AddProjectListId.disabledSubmitBtn();
      }
    });
  },
  init () {
    if (!$(Wick.AddProjectListId.el.loader).length && !$(Wick.AddProjectListId.el.basketLoader).length) {
      appendLoader(Wick.AddProjectListId.loaderPayload);
    }

    Wick.AddProjectListId.disabledSubmitBtn();
    Wick.AddProjectListId.addListenersToAddProjectList();
    Wick.AddProjectListId.clearSearchInputOnPageLeave();
  }
}

$(document).ready(function () {
  Wick.AddProjectListId.init();
});
