import {createEvent} from "./utils/create-event";
import {appendLoader, showLoader, hideLoader} from "./utils/loader";

var Wick = window.Wick || {};

Wick.MyOrders = {
  events: {
    MONTHLY_VIEW_EVENT: 'MONTHLY_VIEW_EVENT',
    SORT_BY_EVENT: 'SORT_BY_EVENT',
    LOAD_MORE_EVENT: 'LOAD_MORE_EVENT',
    CATEGORY_EVENT: 'CATEGORY_EVENT',
  },
  HIDDEN_CLASS_NAME: 'd-none',
  el: {
    $myOrders: $('.my-orders'),
    calendar: '#calendarInputFlatpickr',
    loader: '.loader-wrapper',
    $sortOrders: $('#sort_orders'),
    $chooseDate: $('.flatpickr-datepicker[choose-date]'),
    $showYears: $('.flatpickr-datepicker[show-years]'),
    $desktopTabs: $('.nav-orders .nav-orders__item .link'),
    $mobileTabs: $('.nav-orders .account-nav__link'),
    $loadMoreBtn: $('.btn-load-more'),
    oderList: '.active-orders',
    $activeOrderState: $('.nav-orders .nav-orders__item.active .link')
  },
  initialPageNumber: 0,
  numberOfPagesOrders: $('#numberOfPagesOrders').val(),
  loaderPayload: {
    wrapper: 'body',
    hidden: true,
    modifier: 'basket-loader',
  },
  chooseDate: '',
  showYears: '',
  getChooseDate () {
    const attrValue = Wick.MyOrders.el.$chooseDate.attr('choose-date');
    if (attrValue) {
      Wick.MyOrders.chooseDate = attrValue
    }
  },
  requestToUpdateOrders (currentEvent, payload) {
    return new Promise((resolve, reject) => {
      const eventDetail = {resolve, reject};
      const event = createEvent(currentEvent, payload, eventDetail);
      window.dispatchEvent(event);
    })
      .then(({url}) => {
        if (!url) {
          return;
        }

        window.location.href = url;
      })
      .catch((error) => {
        console.error(error);
      });
  },
  loadMore () {
    showLoader(Wick.MyOrders.el.loader);

    return new Promise((resolve, reject) => {
      const eventDetail = {resolve, reject};
      const payload = {
        currentPage: ++Wick.MyOrders.initialPageNumber,
        sort: Wick.MyOrders.el.$sortOrders.val() || '',
        chooseDate: Wick.MyOrders.chooseDate,
        orderState: Wick.MyOrders.getCurrentOrderState() || ''
      };
      const event = createEvent(Wick.MyOrders.events.LOAD_MORE_EVENT, payload, eventDetail);
      window.dispatchEvent(event);
    })
      .then(({innerHTML, callback}) => {
        if (!innerHTML) {
          return;
        }

        Wick.MyOrders.showNewOrders(innerHTML);
        Wick.MyOrders.toggleLoadMoreBtn();

        if (callback) {
          callback()
        }
      })
      .finally(() => {
        hideLoader(Wick.MyOrders.el.loader);
        Wick.MyOrders.el.$loadMoreBtn.blur();
      })
  },
  showNewOrders (newProductsHtml) {
    const $newProductsHtml = $(newProductsHtml);
    $(Wick.MyOrders.el.oderList).append($newProductsHtml);
  },
  toggleLoadMoreBtn () {
    if (Wick.MyOrders.initialPageNumber + 1 >= +Wick.MyOrders.numberOfPagesOrders) {
      Wick.MyOrders.el.$loadMoreBtn.addClass(Wick.MyOrders.HIDDEN_CLASS_NAME);
    }
  },
  getShowYears () {
    const attrValue = Wick.MyOrders.el.$showYears.attr('show-years');
    if (attrValue) {
      Wick.MyOrders.showYears = attrValue
    }
  },
  initializeFlatpickr () {
    Wick.Flatpickr.init({
      id: Wick.MyOrders.el.calendar,
      currentYear: new Date().getFullYear(),
      minYear: new Date().getFullYear() - Wick.MyOrders.showYears,
      dateFormat: "F Y",
      static: true,
      chooseDate: Wick.MyOrders.chooseDate,
      onChangeCallback: function (dateStr) {
        if (!dateStr || isNaN(new Date(dateStr))) {
          Wick.MyOrders.chooseDate = "";
        } else {
          Wick.MyOrders.chooseDate = dateStr;
        }

        Wick.MyOrders.requestToUpdateOrders(Wick.MyOrders.events.MONTHLY_VIEW_EVENT, { chooseDate: Wick.MyOrders.chooseDate });
      },
    });
  },
  initializeSortOrdersHandler () {
    Wick.MyOrders.el.$sortOrders.on('change', function () {
      const selectedValue = $(this).val();
      Wick.MyOrders.requestToUpdateOrders(Wick.MyOrders.events.SORT_BY_EVENT, { sortBy: selectedValue });
    });
  },
  registerTabClickHandler (tabsElement) {
    tabsElement.on('click', function (e) {
      e.preventDefault();
      const tabId = $(this).attr('id');
      const orderState = tabId ? { orderState: tabId } : '';
      Wick.MyOrders.requestToUpdateOrders(Wick.MyOrders.events.CATEGORY_EVENT, orderState);
    });
  },
  handleCategoryTabClick () {
    Wick.MyOrders.registerTabClickHandler(Wick.MyOrders.el.$desktopTabs);
    Wick.MyOrders.registerTabClickHandler(Wick.MyOrders.el.$mobileTabs);
  },
  getCurrentOrderState () {
    if (Wick.MyOrders.el.$activeOrderState.length) {
      return Wick.MyOrders.el.$activeOrderState.attr('id')
    }
  },
  init () {
    Wick.MyOrders.getShowYears();
    Wick.MyOrders.getChooseDate();
    Wick.MyOrders.initializeFlatpickr();
    Wick.MyOrders.initializeSortOrdersHandler()
    Wick.MyOrders.handleCategoryTabClick();
    appendLoader(Wick.MyOrders.loaderPayload);
    Wick.MyOrders.el.$loadMoreBtn.on('click', Wick.MyOrders.loadMore);
    Wick.HandleAccordions.handleOutsideClick();
  }
}

$(document).ready(function () {
  if (!Wick.MyOrders.el.$myOrders.length) {
    return;
  }

  Wick.MyOrders.init();
});
