import Handlebars from "hbsfy/runtime";
import savedProjectListItem from "../../../components/saved-project-list-item.hbs";

import {appendLoader, showLoader, hideLoader} from "../utils/loader";
import {paintPagination, addPaginationEvent, removePaginationFocus} from "./pagination";

Handlebars.registerPartial('checkbox', require("../../../elements/checkbox.hbs"));

var Wick = window.Wick || {};

Wick.SavingShoppingList = {
  HIDDEN_CLASS_NAME: 'd-none',
  NEW_SAVE_INFO_TEXT: 'Saved to new list: ',
  SAVE_INFO_TEXT: 'Saved to list: ',
  SELECT_PROJECT_LIST_EVENT: 'selectProjectList',
  CREATE_PROJECT_LIST_EVENT: 'createProjectList',
  GET_PROJECT_LISTS_EVENT: 'getProjectLists',
  modalStates: {
    projectLists: 'projectLists',
    projectListProducts: 'projectListProducts',
  },
  el: {
    createNewList: '.create-new-list',
    createNewListBtn: '.create-new-list__btn',
    createNewListBtnOpenClass: 'create-new-list__btn--open',
    createNewListForm: '.create-new-list__form',
    createNewListToggle: '.create-new-list__action',
    projectListAddedCheck: '.added-project__list .chb',
    existingProjectList: '.added-project__list',
    addedProjectList: '.added-project__projects',
    addedProjectListLargeClass: 'added-project__projects--large',
    savedListTextEl: '.saved-new-info',
    continueShoppingBtn: '.saved-action-link button',
    modalSavingToShopList: '#modal-saving-to-shop-list',
    modalContent: '.modal-content.shopping-list',
    projectListName: '#new-project-list-name',
    formRow: '.form-row',
    formRowInfo: '.form-row__error',
    listName: '.saved-to-list_list-name',
    savedProducts: '.saved-products',
    savedProduct: '.saved-product',
    listError: '.list-error',
    listErrorText: '.list-error__text',
    loader: '.modal-content.shopping-list .loader-wrapper',
    goToButton: '.saved-action-link__go-to',
    paginationWrapper: '.added-project__pagination',
    clearBtn: '.btn--clear',
  },
  maxAmountMessage: 'Maximum product quantity reached',
  isMaximumAmountOfShoppingListsReached: null,
  initialPageNumber: 1,
  loaderPayload: {
    wrapper: '.modal-content.shopping-list',
    hidden: true,
    modifier: "shopping-list-loader",
  },
  boundEvents: false,
  changeState(state) {
    $(Wick.SavingShoppingList.el.modalContent).attr('data-action', state);
  },
  toggleAddNewForm() {
    Wick.SavingShoppingList.hideInputError();
    Wick.SavingShoppingList.cleanNameField();
    Wick.SavingShoppingList.toggleCreateBtnState();
    Wick.SavingShoppingList.toggleLargeProjectList();
    $(Wick.SavingShoppingList.el.createNewListForm).toggleClass(Wick.SavingShoppingList.HIDDEN_CLASS_NAME);
  },
  toggleLargeProjectList() {
    $(Wick.SavingShoppingList.el.addedProjectList).toggleClass(Wick.SavingShoppingList.el.addedProjectListLargeClass);
  },
  toggleCreateBtnState() {
    $(Wick.SavingShoppingList.el.createNewListBtn)
      .toggleClass(Wick.SavingShoppingList.el.createNewListBtnOpenClass);
  },
  removeCreateBtnState() {
    $(Wick.SavingShoppingList.el.createNewListBtn)
      .removeClass(Wick.SavingShoppingList.el.createNewListBtnOpenClass);
  },
  hideAddNewForm() {
    $(Wick.SavingShoppingList.el.createNewListForm).addClass(Wick.SavingShoppingList.HIDDEN_CLASS_NAME);
    Wick.SavingShoppingList.removeCreateBtnState();
  },
  createNewList(e) {
    e.preventDefault();
    const projectListName = $(Wick.SavingShoppingList.el.projectListName).val() || '';

    Wick.SavingShoppingList.hideErrors();
    showLoader();

    return new Promise((resolve, reject) => {
      const payload = {
        projectListName: projectListName.trim(),
      }
      const eventDetail = {resolve, reject};
      const event = Wick.SavingShoppingList.createEvent(Wick.SavingShoppingList.CREATE_PROJECT_LIST_EVENT, payload, eventDetail);
      window.dispatchEvent(event);
    })
      .then(Wick.SavingShoppingList.handleListCreation)
      .catch(Wick.SavingShoppingList.handleListCreationError)
      .finally(() => {
        Wick.SavingShoppingList.cleanNameField();
        Wick.SavingShoppingList.disabledCreateBtn();
        Wick.SavingShoppingList.checkVisibilityOfClearButton();
        hideLoader();
      });
  },
  handleListCreation(savedListResponse) {
    Wick.SavingShoppingList.changeState(Wick.SavingShoppingList.modalStates.projectListProducts);
    Wick.SavingShoppingList.updateListInfo(Wick.SavingShoppingList.NEW_SAVE_INFO_TEXT);
    Wick.SavingShoppingList.updateProductList(savedListResponse);
    Wick.SavingShoppingList.updateProjectLists(savedListResponse);
    Wick.SavingShoppingList.changeGoToButtonUrl(savedListResponse.currentProjectList);
  },
  handleListCreationError(error) {
    Wick.SavingShoppingList.showInputError(error.message);
    Wick.SavingShoppingList.cleanNameField();
  },
  selectExistingList() {
    Wick.SavingShoppingList.hideErrors();
    showLoader();

    const projectListId = $(this).find('input').attr('id');

    return new Promise((resolve, reject) => {
      const payload = {
        projectListId: projectListId,
      };
      const eventDetail = {resolve, reject};
      const event = Wick.SavingShoppingList.createEvent(Wick.SavingShoppingList.SELECT_PROJECT_LIST_EVENT, payload, eventDetail);
      window.dispatchEvent(event);
    })
      .then(Wick.SavingShoppingList.handleListSelect)
      .catch(Wick.SavingShoppingList.handleListSelectError)
      .finally(() => hideLoader())
  },
  handleListSelect(selectedListResponse) {
    Wick.SavingShoppingList.changeState(Wick.SavingShoppingList.modalStates.projectListProducts);
    Wick.SavingShoppingList.updateListInfo(Wick.SavingShoppingList.SAVE_INFO_TEXT);
    Wick.SavingShoppingList.updateProductList(selectedListResponse);
    Wick.SavingShoppingList.changeGoToButtonUrl(selectedListResponse.currentProjectList);
  },
  handleListSelectError(error) {
    Wick.SavingShoppingList.showGlobalListError(error.message);
    Wick.SavingShoppingList.unselectCheckboxes();
  },
  handleGetList(getProjectListResponse) {
    Wick.SavingShoppingList.paintProjectList(getProjectListResponse.projectLists);
    Wick.SavingShoppingList.addPagination(getProjectListResponse);
  },
  createEvent(eventName, payload, eventDetail) {
    return new CustomEvent(eventName, {
      detail: {
        payload,
        resolve: eventDetail.resolve,
        reject: eventDetail.reject,
      },
    });
  },
  getProjectLists(pageNumber = Wick.SavingShoppingList.initialPageNumber) {
    Wick.SavingShoppingList.hideErrors();
    showLoader();

    return new Promise((resolve, reject) => {
      const payload = {
        page: pageNumber,
      }
      const eventDetail = {resolve, reject};
      const event = Wick.SavingShoppingList.createEvent(Wick.SavingShoppingList.GET_PROJECT_LISTS_EVENT, payload, eventDetail);
      window.dispatchEvent(event);
    })
      .then(Wick.SavingShoppingList.handleGetList)
      .catch(Wick.SavingShoppingList.handleListSelectError)
      .finally(() => {
        hideLoader();
        removePaginationFocus();
      });
  },
  updateProductList(listInfo) {
    const currentList = listInfo.currentProjectList;

    Wick.SavingShoppingList.updateListName(currentList.name);
    Wick.SavingShoppingList.paintSavedProducts(currentList.products);
  },
  updateListName(name) {
    $(Wick.SavingShoppingList.el.listName).text(name);
  },
  updateListInfo(info) {
    $(Wick.SavingShoppingList.el.savedListTextEl).text(info);
  },
  cleanSavedProducts() {
    $(Wick.SavingShoppingList.el.savedProducts).empty();
  },
  paintSavedProducts(products) {
    const container = $(Wick.SavingShoppingList.el.savedProducts);

    Wick.SavingShoppingList.cleanSavedProducts();

    products.forEach((product) => {
      container.append(Wick.SavingShoppingList.createProductComponent(product))
    })
  },
  updateProjectLists(listInfo) {
    const maxAmountOfProjects = listInfo.maxAmountOfProjects;
    const existingListsAmount = listInfo.projectListLength;
    Wick.SavingShoppingList.isMaximumAmountOfShoppingListsReached = existingListsAmount >= maxAmountOfProjects;
    Wick.SavingShoppingList.isMaximumAmountOfShoppingListsReached
      ? Wick.SavingShoppingList.showMaximumReachedError()
      : Wick.SavingShoppingList.hideMaximumReachedError()
  },
  showMaximumReachedError() {
    $(Wick.SavingShoppingList.el.listError).removeClass(Wick.SavingShoppingList.HIDDEN_CLASS_NAME)
    $(Wick.SavingShoppingList.el.createNewList).addClass(Wick.SavingShoppingList.HIDDEN_CLASS_NAME)
  },
  hideMaximumReachedError() {
    $(Wick.SavingShoppingList.el.listError).addClass(Wick.SavingShoppingList.HIDDEN_CLASS_NAME)
    $(Wick.SavingShoppingList.el.createNewList).removeClass(Wick.SavingShoppingList.HIDDEN_CLASS_NAME)
  },
  paintProjectList(list) {
    const container = $(Wick.SavingShoppingList.el.existingProjectList);
    container.empty();
    list.forEach((listItem) => {
      if (listItem.isFull) {
        listItem.maxAmountMessage = Wick.SavingShoppingList.maxAmountMessage;
      }
      Wick.SavingShoppingList.createListItem(listItem);
    })
  },
  addPagination(response) {
    const payload = {
      container: Wick.SavingShoppingList.el.paginationWrapper,
      currentPage: response.currentPage,
      pagesLength: response.pagesLength
    }

    paintPagination(payload);
  },
  createListItem(listItem) {
    const container = $(Wick.SavingShoppingList.el.existingProjectList);

    container.append(savedProjectListItem(listItem));
  },
  createProductComponent: function (product) {
    return `
      <div class="col-12 info-container saved-product">
        <div class="saved-content">
          <div class="saving-item-picture">
            <img src="${product.image}" alt="${product.name}">
          </div>
          <div class="saved-content__info">
            <div class="saving-name">
              <span class="heading-6">${product.name}</span>
            </div>
            <div>
              <div class="order-item__quant">
                <div class="order-item__quant-title">Quantity:</div>
                <div class="order-item__quant-value">
                  <span class="order-item__value">${product.quantity}</span>
                </div>
              </div>

              <div class="order-item__price">
                <div class="order-item__price-title">Item total:</div>
                <div class="order-item__price-value">
                  <span class="order-item__value">${product.itemTotal}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    `
  },
  showInputError(message) {
    $(Wick.SavingShoppingList.el.formRowInfo).text(message);
    $(Wick.SavingShoppingList.el.formRow).addClass('form-row_validation-error');
  },
  showGlobalListError(message) {
    $(Wick.SavingShoppingList.el.listError).removeClass(Wick.SavingShoppingList.HIDDEN_CLASS_NAME);
    $(Wick.SavingShoppingList.el.listErrorText).text(message);
  },
  hideInputError() {
    $(Wick.SavingShoppingList.el.formRow).removeClass('form-row_validation-error')
  },
  hideGlobalListError() {
    $(Wick.SavingShoppingList.el.listError).hasClass(Wick.SavingShoppingList.HIDDEN_CLASS_NAME)
    || $(Wick.SavingShoppingList.el.listError).addClass(Wick.SavingShoppingList.HIDDEN_CLASS_NAME);
  },
  resetModalState() {
    Wick.SavingShoppingList.cleanNameField();
    Wick.SavingShoppingList.changeState(Wick.SavingShoppingList.modalStates.projectLists);
    Wick.SavingShoppingList.hideAddNewForm();
    Wick.SavingShoppingList.hideErrors();
  },
  hideErrors() {
    Wick.SavingShoppingList.hideInputError();
    Wick.SavingShoppingList.isShoppingListFull() || Wick.SavingShoppingList.hideGlobalListError();
  },
  cleanNameField() {
    $(Wick.SavingShoppingList.el.projectListName).val('');
  },
  unselectCheckboxes() {
    $(Wick.SavingShoppingList.el.projectListAddedCheck).find('input').prop("checked", false);
  },
  changeGoToButtonUrl(currentProjectList) {
    $(Wick.SavingShoppingList.el.goToButton).attr('href', currentProjectList.link);
  },
  isShoppingListFull() {
    return Wick.SavingShoppingList.isMaximumAmountOfShoppingListsReached;
  },
  disabledCreateBtn() {
    $(Wick.SavingShoppingList.el.createNewListToggle)
      .prop('disabled', $(Wick.SavingShoppingList.el.projectListName).val().length === 0);
  },
  handleCreateInput() {
    Wick.SavingShoppingList.disabledCreateBtn();
    Wick.SavingShoppingList.checkVisibilityOfClearButton();

  },
  checkVisibilityOfClearButton() {
    $(Wick.SavingShoppingList.el.clearBtn)
      .toggleClass('d-block', $(Wick.SavingShoppingList.el.projectListName).val().length > 0);
  },
  handleClearEvent() {
    Wick.SavingShoppingList.disabledCreateBtn();
    Wick.SavingShoppingList.checkVisibilityOfClearButton();
    Wick.SavingShoppingList.hideInputError();
  },
  bindEvents() {
    $(Wick.SavingShoppingList.el.createNewListToggle).on("click", Wick.SavingShoppingList.createNewList);
    $(Wick.SavingShoppingList.el.projectListName).on("submit", Wick.SavingShoppingList.createNewList);
    $(Wick.SavingShoppingList.el.createNewListBtn).on("click", Wick.SavingShoppingList.toggleAddNewForm);
    $(Wick.SavingShoppingList.el.continueShoppingBtn).on("click", Wick.SavingShoppingList.resetModalState);
    $(Wick.SavingShoppingList.el.modalContent).on("change", Wick.SavingShoppingList.el.projectListAddedCheck, Wick.SavingShoppingList.selectExistingList);
    $(Wick.SavingShoppingList.el.modalSavingToShopList).on('hide.bs.modal', Wick.SavingShoppingList.resetModalState);
    $(Wick.SavingShoppingList.el.projectListName).on('input', Wick.SavingShoppingList.handleCreateInput);
  },
  init() {
    if (!$(Wick.SavingShoppingList.el.loader).length) {
      appendLoader(Wick.SavingShoppingList.loaderPayload);
    }

    if (Wick.SavingShoppingList.boundEvents !== true) {
      Wick.SavingShoppingList.boundEvents = true;
      Wick.SavingShoppingList.bindEvents();
    }

    Wick.SavingShoppingList.getProjectLists();
    addPaginationEvent(Wick.SavingShoppingList.el.paginationWrapper, Wick.SavingShoppingList.getProjectLists);
    $(document).on('clearInput', Wick.SavingShoppingList.handleClearEvent);
  }
};
