export default class ProductSets {
   constructor(customOptions) {
      const defaultOptions = {
         $selectedWrapper: $('[data-sets="selected-wrapper"]')
      };

      this.options = { ...defaultOptions, ...customOptions };
      this.$selectedWrapper = this.options.$selectedWrapper;

      this.isSetCompleted();
      this.updateDiscount();

      const $setsWrapper = $('[data-sets="wrapper"]');
      const me = this;

      $setsWrapper.on('change', 'input[name="IDvariation"]', function() {
         me.updateBuyButton($(this).closest('.inner'), true);
      });

      $('[data-set-modal]').on('click', function(e) {
         e.preventDefault();
         me.modalOpen($(this));
         return false;
      });

      $('[data-add-to-set]').on('click', function(e) {
         me.productAddCallback(e, $(this));
      });
   }

   isSetCompleted() {
      var $requiredItems = this.$selectedWrapper.find('[data-sets="selected-item"]').length;
      var $selectedItems = this.$selectedWrapper.find('[data-sets="selected-item"].item-selected').length;

      if ($requiredItems > $selectedItems) {
         this.incompleteCallback();
      } else {
         this.completeCallback();
      }
   }

   completeCallback() {
      $('[data-submit-btn]').attr('disabled', false);

      this.updateTotalPrice();
   }

   incompleteCallback() {
      $('[data-submit-btn]').attr('disabled', true);
      $('[data-set-price-complete]').hide();
      $('[data-set-price-uncomplete]').show();
   }

   navCallback(e, $elem) {
      e.preventDefault();
      var $modal = $elem.parents('.focus-content');
      this.navigateInModal($modal.find('.inner.active'), $modal.find('.inner').length, this, $elem.data('direction'));
      return false;
   }

   modalOpen($elem) {
      $('.product-set-focus .inner').removeClass('active');
      var productId = $elem.data('product-id');
      var categoryId = $elem.data('category-id');
      var $focus = $('.product-set-focus[data-category="' + categoryId + '"]');
      var item = $focus.find('.inner[data-product="' + productId + '"]').addClass('active');

      this.updateNavigation($focus, item.data('position'), $focus.find('.inner').length);

      this.checkSelectedSetVariation(item);
      //wpj.productSets.customModal(item);

      $focus.focus();
      $focus.focus('show');
   }

   productAddCallback(e, $elem) {
      e.preventDefault();

      var $form = $elem.parents('.inner'),
          $categoryId = $form.find('input[name=IDcategory]').val(),
          $productId = $form.find('input[name=IDproduct]').val(),
          $variation = $form.find('input[name=IDvariation]:checked')
             ? $form.find('input[name=IDvariation]:checked')
             : $form.find('input[name=IDvariation]'),
          $variationId = $variation.val(),
          $image = $form.find('input[name=image]').val(),
          $price = $form.find('input[name=price]').val(),
          $priceOriginal = $form.find('input[name=priceOriginal]').val(),
          $selectedItemBox = $('#set-part-' + $categoryId);

      $('input[name="note[sets][' + $categoryId + '][id_product]"]').val($productId);
      $('input[name="note[sets][' + $categoryId + '][id_variation]"]').val($variationId);

      $selectedItemBox.find('img').attr('src', $image);
      $selectedItemBox.attr('data-price', $price);
      $selectedItemBox.attr('data-price-original', $priceOriginal);
      $selectedItemBox
         .find('[data-size]')
         .text($form.find('[name="IDvariation"]:checked').next('label').find('span').text());

      if ($variationId) {
         $selectedItemBox.find('p').show();
      } else {
         $selectedItemBox.find('p').hide();
      }

      var variations = [];
      $form.find('.variation-active').each(function() {
         var $this = $(this);
         var variation = {
            value: $this.find('.variation-title').text()
         };

         variations.push(variation);
      });

      var variation_result = '';
      for (var i = 0; i < variations.length; i++) {
         variation_result = variation_result + variations[i].value;

         if (i < variations.length - 1) {
            variation_result = variation_result + ' | ';
         }
      }

      $selectedItemBox.find('[data-variations]').html(variation_result);

      $selectedItemBox.addClass('item-selected');

      $('[data-item-selection][data-category-id="' + $categoryId + '"]').removeClass('item-selected');
      $('[data-item-selection][data-product="' + $productId + '"]').addClass('item-selected');

      var $focus = $('.product-set-focus[data-category="' + $categoryId + '"]');
      $focus.focus('hide');

      this.isSetCompleted();
      this.updateDiscount();

      return false;
   }

   /* customModal: function(modal) {
       try {
          var options = {
             'modal': modal,
          };
          productSetModalCustom(options);
       } catch (e) {
          console.log(e);
       }
    },*/

   updateNavigation(modal, itemPosition, itemsCount) {
      var navItemPrev = modal.find('[data-product-set-nav][data-direction="prev"]');
      var navItemNext = modal.find('[data-product-set-nav][data-direction="next"]');

      if (itemsCount === 1) {
         navItemNext.hide();
         navItemPrev.hide();
         return;
      }

      if (parseInt(itemPosition) === 1) {
         navItemPrev.addClass('disabled');
         navItemNext.removeClass('disabled');
      } else if (parseInt(itemPosition) === itemsCount) {
         navItemPrev.removeClass('disabled');
         navItemNext.addClass('disabled');
      } else {
         navItemPrev.removeClass('disabled');
         navItemNext.removeClass('disabled');
      }
   }

   navigateInModal(item, itemsCount, navigationItem, direction) {
      var itemToShow;
      $(item).removeClass('active');

      if (direction === 'prev') {
         itemToShow = $(item)
            .prev()
            .addClass('active');
      } else {
         itemToShow = $(item)
            .next()
            .addClass('active');
      }

      this.updateNavigation(item.parents('.focus-content'), itemToShow.data('position'), itemsCount);
      //this.checkSelectedSetVariation(itemToShow);
      //this.customModal(itemToShow);
   }

   checkSelectedSetVariation(modal) {
      var $allSetVariations = modal.find('[data-set-variations="variations"]');

      if ($allSetVariations.length > 0) {
         this.updateBuyButton(modal, $allSetVariations.find('input:checked').length > 0);
      }
   }

   updateBuyButton(modal, inStore) {
      var buyButton = modal.find('[data-add-to-set]');

      if (inStore) {
         buyButton.attr('disabled', false);
      } else {
         buyButton.attr('disabled', true);
      }
   }

   updateTotalPrice() {
      var totalPrice = 0;
      var originalPrice = 0;

      $('[data-set-price-complete]').show();
      $('[data-set-price-uncomplete]').hide();

      this.$selectedWrapper
         .find('.item-selected')
         .each(function() {
            totalPrice += parseInt($(this).attr('data-price'));
            originalPrice += parseInt($(this).attr('data-price-original'));
         });

      $('[data-set-price-complete] [data-price]').text(totalPrice.toLocaleString());
      $('[data-set-price-complete] [data-price-original]').text((originalPrice - totalPrice).toLocaleString());

      if (originalPrice === totalPrice && $('[data-set-price-complete] .discount').length) {
         $('[data-set-price-complete] .discount')[0].textContent = '';
      }
   }

   updateDiscount() {
      var discountBox = $('[data-discount]'),
          setPrice = parseInt(discountBox.data('price-total')),
          items = this.$selectedWrapper.find('.item'),
          itemsPrice = 0;

      items.each(function() {
         itemsPrice += parseInt($(this).data('price'));
      });

      discountBox.html(itemsPrice - setPrice);
   }
}
