import {createEvent} from "../utils/create-event";
import globalSearchBody from "../../../partials/global-search-body.hbs";
import {hideLoader, showLoader} from "../utils/loader";
import {isKeyboardOpen} from "../utils/helpers";

const Handlebars = require("hbsfy/runtime");
Handlebars.registerHelper('lt', function(a, b) {
  return a < b;
});
Handlebars.registerHelper('ifCond', function (v1, operator, v2, options) {
  if (operator === '||') {
    return (v1 || v2) ? options.fn(this) : options.inverse(this);
  }
});

var Wick = window.Wick || {};

Wick.GlobalSearch = {
  SEARCH_PRODUCTS_EVENT: 'searchProductEvent',
  el: {
    $searchBtn: $('#search-button'),
    $searchInput: $('.header-global-search__form #search'),
    $headerGlobalSearchForm: $('.header-global-search__form'),
    $header: $('.header'),
    $btnBack: $('.btn--back'),
    $btnClear: $('.header-global-search__form .btn--clear'),
    $globalSearchTab: $('.global-search'),
    $globalSearchWrapper: $('.global-search__wrapper'),
    $headerGlobalSearch: $('.header-global-search'),
    $loaderSpinner: $('.search-loader .loader-spinner'),
    searchLoader: '.search-loader',
    headerSearchActiveClass: 'header--search-active',
    buttonSearchActiveClass: 'search--active',
  },
  isGlobalSearchWrapperActive: true,
  isGlobalSearchActive () {
    return Wick.GlobalSearch.el.$globalSearchTab.is(":visible");
  },
  getSearchProduct () {
    Wick.GlobalSearch.checkVisibilityOfClearButton();
    Wick.GlobalSearch.debounceRequest();
  },
  toggleSearchFormActiveState () {
    if (Wick.GlobalSearch.el.$headerGlobalSearch.is(":visible")) {
      Wick.GlobalSearch.el.$headerGlobalSearchForm.addClass('active');

      if (!Wick.GlobalSearch.isGlobalSearchActive()) {
        Wick.GlobalSearch.checkVisibilityOfClearButton();
        Wick.GlobalSearch.debounceRequest();
      }
    }
  },
  removeSearchFormActiveState () {
    Wick.GlobalSearch.el.$headerGlobalSearchForm.removeClass('active');
  },
  getSearchValue () {
    return Wick.GlobalSearch.el.$searchInput.val();
  },
  checkVisibilityOfClearButton() {
    Wick.GlobalSearch.el.$btnClear.toggleClass('d-block', Wick.GlobalSearch.getSearchValue().length > 0);
  },
  debounceRequest: _.debounce(() => {
    if (Wick.GlobalSearch.getSearchValue().length >= 2) {
      Wick.GlobalSearch.resizeLoaderSpinnerWhenKeyboardOpen();
      Wick.GlobalSearch.sendRequest();
    } else {
      Wick.GlobalSearch.hideContentWrapper();
    }
  }, 250),
  sendRequest () {
    const searchValue = Wick.GlobalSearch.getSearchValue();
    const transformSearchValue = searchValue.replace(/[\[\]\<\>\(\)\/\{\}\!\@\$\#\%\^\*]/g, "");

    if (Wick.GlobalSearch.isGlobalSearchWrapperActive) {
      Wick.GlobalSearch.el.$globalSearchTab.addClass('d-block');
      showLoader(Wick.GlobalSearch.el.searchLoader);
    }

    return new Promise((resolve, reject) => {
      const payload = {
        value: transformSearchValue,
      }
      const eventDetail = {resolve, reject};
      const event = createEvent(Wick.GlobalSearch.SEARCH_PRODUCTS_EVENT, payload, eventDetail);
      window.dispatchEvent(event);
    })
      .then(({suggestions, products, contentPages}) => {
        Wick.GlobalSearch.showContentWrapper(suggestions, products, contentPages);

        if (!suggestions && !products && !contentPages) {
          Wick.GlobalSearch.isGlobalSearchWrapperActive = false;
        } else {
          Wick.GlobalSearch.isGlobalSearchWrapperActive = true;
          Wick.GlobalSearch.el.$globalSearchTab.addClass('d-block');
        }
      })
      .catch(() => {
        Wick.GlobalSearch.isGlobalSearchWrapperActive = false;
        Wick.GlobalSearch.el.$globalSearchTab.removeClass('d-block');
      })
      .finally(() => {
        hideLoader(Wick.GlobalSearch.el.searchLoader);
      })
  },
  showContentWrapper (suggestions, product, contentPages) {
    const newContent = globalSearchBody({
      suggestions: suggestions,
      products: product,
      contentPages: contentPages,
    });

    if (!suggestions && !product && !contentPages) {
      Wick.GlobalSearch.el.$globalSearchTab.removeClass('d-block');
    } else {
      Wick.GlobalSearch.el.$globalSearchWrapper.html(newContent);
    }
  },
  toggleVisibilityOfSearchInputOnMobile (e) {
    e.stopPropagation();
    Wick.GlobalSearch.el.$headerGlobalSearch.toggle();
    Wick.GlobalSearch.el.$header.addClass(Wick.GlobalSearch.el.headerSearchActiveClass)
    Wick.GlobalSearch.debounceRequest();
    Wick.GlobalSearch.el.$searchInput.focus();
  },
  hideContentWrapper () {
    Wick.GlobalSearch.el.$globalSearchWrapper.html('');
    Wick.GlobalSearch.el.$globalSearchTab.removeClass('d-block');
  },
  searchButtonBackClick (e) {
    e.stopPropagation();
    Wick.GlobalSearch.removeActiveClasses();
  },
  closeSearchOnClickOutside (e) {
    if (
      !Wick.GlobalSearch.el.$headerGlobalSearch.is(e.target)
      && Wick.GlobalSearch.el.$headerGlobalSearch.has(e.target).length === 0
      && Wick.GlobalSearch.isGlobalSearchActive()
    ) {
      Wick.GlobalSearch.removeActiveClasses();
    }
  },
  removeActiveClasses () {
    if (Wick.Responsive.getCurrentBreakpoint() === 'down-sm') {
      Wick.GlobalSearch.el.$headerGlobalSearch.toggle();
      Wick.GlobalSearch.el.$globalSearchTab.removeClass('d-block');
      Wick.GlobalSearch.el.$header.removeClass(Wick.GlobalSearch.el.headerSearchActiveClass);
      Wick.GlobalSearch.el.$searchBtn.removeClass(Wick.GlobalSearch.el.buttonSearchActiveClass);
    }

    Wick.GlobalSearch.el.$globalSearchTab.removeClass('d-block');
  },
  resizeLoaderSpinnerWhenKeyboardOpen () {
    const globalSearchTabHeight = Wick.GlobalSearch.el.$globalSearchTab.height();
    const screenHeightWithoutKeyboard = window.visualViewport.height;

    if (
      Wick.Responsive.getCurrentBreakpoint() === 'down-sm'
      && isKeyboardOpen()
      && screenHeightWithoutKeyboard < globalSearchTabHeight
    ) {
      Wick.GlobalSearch.el.$loaderSpinner.css('height', window.visualViewport.height + 'px');
    } else {
      Wick.GlobalSearch.el.$loaderSpinner.removeAttr('style');
    }
  },
  addListenersToSearchElements () {
    Wick.GlobalSearch.el.$searchInput.on('input', Wick.GlobalSearch.getSearchProduct);
    Wick.GlobalSearch.el.$btnClear.on('click', Wick.GlobalSearch.hideContentWrapper);
    Wick.GlobalSearch.el.$searchBtn.on('click', Wick.GlobalSearch.toggleVisibilityOfSearchInputOnMobile);
    Wick.GlobalSearch.el.$btnBack.on('click', Wick.GlobalSearch.searchButtonBackClick);
    $(document).on('click', Wick.GlobalSearch.closeSearchOnClickOutside);

    Wick.GlobalSearch.el.$searchInput
      .on('focus', Wick.GlobalSearch.toggleSearchFormActiveState)
      .on('blur', Wick.GlobalSearch.removeSearchFormActiveState);
  },
  init () {
    Wick.GlobalSearch.addListenersToSearchElements();
  }
}

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