(function ($) {
  window.initKristallIntegrationAdditionalContentSettings = function(data, options) {

    /**
     * filter data struct:
     * {
     *   id: int,
     *   filters: [
     *     {
     *       name: type|sku|title,
     *       value?: ...
     *       option?: starts|ends|contains|product|service
     *     },
     *     ...
     *   ]
     * }
     */

    var availableFilters = {
      type: {
        title: 'Тип',
        options: ['product', 'service'],
        hasInput: false
      },
      sku: {
        title: 'SKU',
        options: ['equals', 'starts', 'ends', 'contains']
      },
      title: {
        title: 'Наименование',
        options: ['equals', 'starts', 'ends', 'contains']
      },
    };
    var optionTitles = {
      equals: 'Равно',
      starts: 'Начинается с',
      ends: 'Заканчивается на',
      contains: 'Содержит',
      product: 'Товар',
      service: 'Услуга',
    };
    
    var $wrapper = $('#kristall-integration__additional_content__wrapper');
    if (!$wrapper.length) {
      return;
    }
    var $sideInput = $('#kristall-integration__additional_content__side_input');
    var $descInput = $('#kristall-integration__additional_content__desc_input');
    var $select = $('#kristall-integration__additional_content__select');
    var $addBtn = $('#kristall-integration__additional_content__add');
    var $dd = $('#kristall-integration__additional_content__dropdown');
    var $editorWrapper = $('#kristall-integration__additional_content__wysiwyg_wrapper');

    var $selectPlaceholder = $('#kristall-integration__additional_content__placeholder');
    var $selectText = $('#kristall-integration__additional_content__selected_text');
    var $selectFilters = $('#kristall-integration__additional_content__selected_filters');
    var $removeWrapper = $('#kristall-integration__additional_content__remove_wrapper');

    var lastId = 0;
    var selectedId;
    var preventUpdate = false;

    var sideContents = JSON.parse($sideInput.val()) || [];
    sideContents = sideContents.map(function(item) {
      item.id = ++lastId;
      return item;
    }).sort(function(a, b) {
      return a.filters.length - b.filters.length
    });

    var descContents = JSON.parse($descInput.val()) || [];
    descContents = descContents.map(function (item) {
      item.id = ++lastId;
      return item;
    }).sort(function (a, b) {
      return a.filters.length - b.filters.length
    });

    function escapeHtml(unsafe) {
      return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
    }

    function onEditorContentChange(content) {
      if (preventUpdate) return;

      var item = getItem(selectedId);
      item.content = content;
      updateHiddenInputs();
    }

    function getEditor() {
      $editorWrapper.show();
      var editor = tinymce.get('kristall-integration__additional_content__wysiwyg');

      if ($editorWrapper.attr('data-ki-bound') === 'true') return editor;
      $editorWrapper.attr('data-ki-bound', 'true');

      var $textarea = $('#kristall-integration__additional_content__wysiwyg');

      $textarea.on('change', function () {
        onEditorContentChange($textarea.val());
      });
      editor.on('change', function (e) {
        onEditorContentChange(editor.getContent());
      });
      editor.on('ExecCommand', function () {
        onEditorContentChange(editor.getContent());
      });
      editor.on('undo', function () {
        onEditorContentChange(editor.getContent());
      });
      editor.on('redo', function () {
        onEditorContentChange(editor.getContent());
      });

      $editorWrapper.on('click', '.wp-switch-editor', function () {
        var isMce = $(this).hasClass('switch-tmce');

        setTimeout(function () {
          onEditorContentChange(isMce ? editor.getContent() : $textarea.val());
        }, 500)
      });

      return editor;
    }

    $select.on('click', function(e) {
      $select.toggleClass('show');
    });

    $addBtn.on('click', function (e) {
      $addBtn.toggleClass('show');
    });

    $wrapper.on('click', '.kristall-integration__additional_content__filters_add', function (e) {
      e.preventDefault();
      $(e.target).toggleClass('show');
    });

    $dd.on('click', '.kristall-integration__additional_content__dd_item', function(e) {
      e.preventDefault();
      var $el = $(e.target);
      if (!$el.hasClass('.kristall-integration__additional_content__dd_item')) {
        $el = $el.parents('.kristall-integration__additional_content__dd_item');
      }
      activateItem(Number($el.attr('data-id')));
      $select.removeClass('show');
    });

    $wrapper.on('click', '.kristall-integration__additional_content__filters_add_dd .kristall-integration__additional_content__dd_item', function (e) {
      e.preventDefault();
      var $addWrapper = $wrapper.find('.kristall-integration__additional_content__filters_add-wrapper');
      $addWrapper.before(
        getFilter({
          name: $(e.target).attr('data-type')
        })
      );
      $addWrapper.find('.kristall-integration__additional_content__filters_add').removeClass('show');
      filtersChanged();
    });

    $wrapper.on('click', '.kristall-integration__additional_content__filter_remove', function (e) {
      e.preventDefault();
      $(e.target).parents('.kristall-integration__additional_content__filter').remove();
      filtersChanged();
    });

    $wrapper.on('change', '.kristall-integration__additional_content__filter_options', function (e) {
      filtersChanged();
    });

    $wrapper.on('input', '.kristall-integration__additional_content__filter_value', function (e) {
      filtersChanged();
    });

    $('#kristall-integration__additional_content__remove').on('click', function(e) {
      e.preventDefault();

      var item = getItem(selectedId);

      if (!item) {
        return;
      }

      if (!confirm('Вы действительно хотите удалить выбранный контент?')) {
        return;
      }

      if (sideContents.indexOf(item) !== -1) {
        sideContents.splice(
          sideContents.indexOf(item),
          1
        );
      } else {
        descContents.splice(
          descContents.indexOf(item),
          1
        );
      }

      updateHiddenInputs();

      $('#kristall-integration__additional_content__dropdown').find('[data-id=' + selectedId + ']').remove();

      selectedId = null;
      $selectPlaceholder.show();
      $selectText.hide();
      $selectFilters.hide();
      $wrapper.find('.kristall-integration__additional_content__filters').remove();
      $editorWrapper.hide();
      $removeWrapper.hide();
    });

    $('body').on('click', function(e) {
      var $addFilter = $wrapper.find('.kristall-integration__additional_content__filters_add');

      if (
        $select.hasClass('show') &&
        (
          e.target.id !== 'kristall-integration__additional_content__select' &&
          !e.target.closest('#kristall-integration__additional_content__select')
        ) &&
        !e.target.closest('#kristall-integration__additional_content__dropdown')
      ) {
        $select.removeClass('show');
      }

      if (
        $addBtn.hasClass('show') &&
        (
          e.target.id !== 'kristall-integration__additional_content__add' &&
          !e.target.closest('#kristall-integration__additional_content__add')
        ) &&
        !e.target.closest('#kristall-integration__additional_content__dropdown_add')
      ) {
        $addBtn.removeClass('show');
      }

      if (
        $addFilter.hasClass('show') &&
        (
          !$(e.target).hasClass('kristall-integration__additional_content__filters_add') &&
          !e.target.closest('.kristall-integration__additional_content__filters_add')
        ) &&
        !e.target.closest('.kristall-integration__additional_content__filters_add_dd')
       ) {
        $addFilter.removeClass('show'); 
      }
    });

    function getFiltersDescription(filters) {
      var filtersType = '';
      var filtersSku = [];
      var filtersTitle = [];

      filters.forEach(function (filter) {
        var option = filter.option;
        switch (filter.name) {
          case 'type':
            filtersType = 'тип: ' + (filter.option == 'product' ? 'товар' : 'услуга');
            break;
          case 'sku':
            filtersSku.push('sku: ' + (
              option === 'starts' ? filter.value + '*' : (
                option === 'ends' ? '*' + filter.value : (
                  option === 'contains' ? '* ' + filter.value + '*' : filter.value
                )
              )
            ));
            break;
          case 'title':
            filtersTitle.push('наименование: ' + (
              option === 'starts' ? filter.value + '*' : (
                option === 'ends' ? '*' + filter.value : (
                  option === 'contains' ? '*' + filter.value + '*' : filter.value
                )
              )
            ));
            break;
        }
      });

      if (filtersType && (filtersSku.length || filtersTitle.length)) {
        filtersType += '; ';
      }

      return `${filtersType}${filtersSku.join('; ')}${filtersSku.length && filtersTitle.length ? '; ' : ''}${filtersTitle.join('; ')}`;
    }

    function getDdItem(type, settings) {
      var filters = settings.filters ? settings.filters : [];

      if (!settings.id) {
        settings.id = ++lastId;
      }

      return `
        <div class="kristall-integration__additional_content__dd_item" data-id="${settings.id}">
          <div class="kristall-integration__additional_content__selected_text">${type === 'side' ? 'Боковой контент' : 'Дополнительный контент описания'}</div>
          <div class="kristall-integration__additional_content__selected_filters">${getFiltersDescription(filters)}</div>
        </div>
      `;
    }

    function getFilter(filter) {
      var settings = availableFilters[filter.name];

      if (!settings) {
        return '';
      }

      var options = '';
      if (settings.options) {
        var selectedOption = settings.options.indexOf(filter.option) !== -1 ?
          filter.option :
          settings.options[0];

        options = '<select class="kristall-integration__additional_content__filter_options">';
        settings.options.forEach(function (option) {
          options += `<option value="${option}"${option === selectedOption ? ' selected="selected"' : ''}>${optionTitles[option]}</option>`;
        });        
        options += '</select>';
      }

      return `
        <div class="kristall-integration__additional_content__filter${settings.hasInput === false ? ' kristall-integration__additional_content__no_input' : ''}${!options ? ' kristall-integration__additional_content__no_options' : ''}" data-name="${filter.name}">
          <div class="kristall-integration__additional_content__filter_title">${settings.title}</div>
          ${options}
          ${settings.hasInput !== false ? `<input type="text" value="${filter.value ? escapeHtml(filter.value) : ''}" class="kristall-integration__additional_content__filter_value">` : ''}
          <button class="button kristall-integration__additional_content__filter_remove" type="button">&times;</button>
        </div>
      `;
    }

    function getFilterControls (filters) {
      var filtersMarkup = filters.map(function(filter) {
        return getFilter(filter);
      });

      return `
        <div class="kristall-integration__additional_content__filters">
          <div class="kristall-integration__additional_content__filters_add-wrapper">
            ${filtersMarkup.join('')}
            <a href="#" class="kristall-integration__additional_content__filters_add">
              + Добавить фильтр
            </a>
            <div class="kristall-integration__additional_content__filters_add_dd">
              <div class="kristall-integration__additional_content__dd_item" data-type="type">Тип</div>
              <div class="kristall-integration__additional_content__dd_item" data-type="sku">SKU</div>
              <div class="kristall-integration__additional_content__dd_item" data-type="title">Наименование</div>
            </div>
          </div>
        </div>
      `
    }

    function getItem (itemId) {
      var item = sideContents.find(function (i) {
        return i.id === itemId;
      });

      if (!item) {
        item = descContents.find(function (i) {
          return i.id === itemId;
        });
      }

      return item ||null;
    }

    function activateItem (itemId) {
      var item = getItem(itemId);

      if (!item) {
        return;
      }

      var $selectItem = $('.kristall-integration__additional_content__dd_item[data-id=' + itemId + ']');

      $select.removeClass('show');
      $addBtn.removeClass('show');
      selectedId = item.id;
      $selectPlaceholder.hide();
      $selectText.text(
        $selectItem.find('.kristall-integration__additional_content__selected_text').text()
      ).show();
      $selectFilters.text(
        $selectItem.find('.kristall-integration__additional_content__selected_filters').text()
      ).show();

      $wrapper.find('.kristall-integration__additional_content__filters').remove();
      $wrapper.find('.kristall-integration__additional_content__row').after(
        getFilterControls(item.filters || [])
      );

      preventUpdate = true;
      getEditor().setContent(item.content || '');
      preventUpdate = false;
      $removeWrapper.show();
    }

    $('#kristall-integration__additional_content__dropdown_add').on('click', '.kristall-integration__additional_content__dd_item', function() {
      var type = $(this).attr('data-type');

      var data = {
        id: ++lastId,
        type: type,
        filters: []
      };

      if (type === 'side') {
        sideContents.push(data);
      } else {
        descContents.push(data);
      }

      var item = getDdItem(type, data);
      $dd.append(item);

      activateItem(data.id);
    });

    function updateHiddenInputs() {
      $sideInput.val(JSON.stringify(
        sideContents.map(function(item) {
          item = Object.assign({}, item);
          delete item.id;
          delete item.type;
          return item;
        })
      ));
      $descInput.val(JSON.stringify(
        descContents.map(function (item) {
          item = Object.assign({}, item);
          delete item.id;
          delete item.type;
          return item;
        })
      ));
    }

    function filtersChanged() {
      var item = getItem(selectedId);
      
      if (!item) {
        return;
      }

      var filters = [];
      $wrapper.find('.kristall-integration__additional_content__filter').each(function() {
        var $el = $(this);

        var filter = {
          name: $el.attr('data-name')
        }

        var $select = $el.find('.kristall-integration__additional_content__filter_options').first();
        if ($select.length) {
          filter.option = $select.val();
        }

        var $input = $el.find('.kristall-integration__additional_content__filter_value').first();
        if ($input.length) {
          filter.value = $input.val().trim();
          if (!filter.value) {
            return;
          }
        }

        if (!filter.option && !filter.value) return;

        filters.push(filter);
      });

      item.filters = filters;

      var description = getFiltersDescription(filters);
      $('#kristall-integration__additional_content__selected_filters').text(description);
      $dd.find('[data-id=' + selectedId + '] .kristall-integration__additional_content__selected_filters').text(description);

      updateHiddenInputs();
    }

    // Init select
    sideContents.forEach(function (data) {
      $dd.append(getDdItem('side', data));
    });
    descContents.forEach(function (data) {
      $dd.append(getDdItem('description', data));
    });
  }
})(jQuery);
