document.addEventListener('DOMContentLoaded', function() {
  window.containerManufacturedList = document.getElementById('manufactured_list');
  window.info = JSON.parse(document.querySelector('[data-info]').getAttribute('data-info'));

  language.add(info.languages);
  language.load('module/manufactured');

  let newModuleId = containerManufacturedList.querySelectorAll('.js-manufactured').length + 1;

  initRemoveManufactured(containerManufacturedList);

  document.getElementById('addFeatured').onclick = addModule;

  const TOKEN = document.body.dataset.token;

  $('input[name="manufacturer"]').autocomplete({
    delay: 500,
    source: function(request, response) {
      $.ajax({
        url:
          'index.php?route=catalog/manufacturer/autocomplete&token=' +
          TOKEN +
          '&filter_manutecturer=' +
          encodeURIComponent(request.term),
        dataType: 'json',
        method: 'GET',
        success: function(json) {
          response(
            $.map(json, function(item) {
              return {
                label: item.name,
                value: item.manufacturer_id,
              };
            })
          );
        },
        error: function(err) {
          console.log(err);
        },
      });
    },
    select: function(event, ui) {
      const ID = 'manufactured-product' + ui.item.value;

      if (document.getElementById(ID)) return false;

      const DIV = document.createElement('div');
      DIV.id = `manufactured-product${ui.item.value}`;
      DIV.setAttribute('class', 'scrollbox-item flex between-xs');
      DIV.innerHTML = `
        <span class="text-small text-dark">${ui.item.label}</span>
        <i class="fas fa-trash-alt text-small right-margin-small text-error js-btn-remove"></i>
        <input type="hidden" value="${ui.item.value}">
      `;

      document.getElementById('manufactured-product').appendChild(DIV);

      manufacturedListUpdate();
      AddClickListener(DIV);

      return false;
    },
    focus: function(event, ui) {
      return false;
    },
  });

  var removeButton = document.querySelectorAll('.js-btn-remove');
  for (let i = 0; i < removeButton.length; i++) {
    removeButton[i].addEventListener('click', function() {
      this.parentNode.remove();
      manufacturedListUpdate();
    });
  }

  AddClickListener();

  function AddClickListener(context) {
    context = context || document;
    var removeButton = context.querySelectorAll('.js-btn-remove');
    for (var i = 0; i < removeButton.length; i++) {
      removeButton[i].addEventListener('click', function() {
        this.parentNode.remove();
        manufacturedListUpdate();
      });
    }
  }

  function manufacturedListUpdate() {
    var arrData = [];
    var elementList = document.querySelectorAll('#manufactured-product input');
    for (var i = 0; i < elementList.length; i++) {
      arrData.push(elementList[i].value);
    }

    document.querySelector('input[name="manufactured_id"]').setAttribute('value', arrData.join());
  }

  function initRemoveManufactured(context) {
    context = context || document;
    var controlRemoveManufactured = context.querySelectorAll('.js-remove-manufactured');

    for (let i = 0; i < controlRemoveManufactured.length; i++) {
      controlRemoveManufactured[i].onclick = removeManufactured;
    }
  }

  function removeManufactured() {
    var id = this.getAttribute('data-manufactured-id');
    document.getElementById(id).remove();
  }

  function addModule() {
    const LAYOUTS = info.layouts,
      STATUS_LIST = Type_Status.getEnumList(),
      POSITIONS = Type_ModulePosition.getRemoveArray([Type_ModulePosition.Tp_ColumnRight], true),
      MODULE_CONTAINER = document.createElement('div'),
      HTML = `
        <div class="row x-small-space-xs">
        <div class="col-md-width-auto">
        <label class="field field-medium">
        <span class="field-label">${language.get('entry_limit')}</span>
        <input class="field-entry numeric" type="text" maxlength="2" name="manufactured_module[${newModuleId}][limit]" value="" size="1">
        </label>
        </div>
        <div class="col-md">
        <label class="field field-medium">
        <span class="field-label">${language.get('entry_layout')}</span>
        <select class="field-entry" name="manufactured_module[${newModuleId}][layout_id]">
        ${LAYOUTS.map(layout => `<option value="${layout.layout_id}">${layout.name}</option>`).join('')}
        </select>
        </label>
        </div>
        <div class="col-md">
        <label class="field field-medium">
        <span class="field-label">${language.get('entry_position')}</span>
        <select class="field-entry" name="manufactured_module[${newModuleId}][position]">
        ${Object.keys(POSITIONS)
          .map(key => `<option value="${key}">${POSITIONS[key]}</option>`)
          .join('')}
        </select>
        </label>
        </div>
        <div class="col-md">
        <label class="field field-medium">
        <span class="field-label">${language.get('entry_status')}</span>
        <select class="field-entry" name="manufactured_module[${newModuleId}][status]">
        ${Object.keys(STATUS_LIST)
          .map(key => `<option value="${key}">${STATUS_LIST[key]}</option>`)
          .join('')}
        </select>
        </label>
        </div>
        <div class="col-md-width-auto">
        <label class="field field-medium">
        <span class="field-label">${language.get('entry_sort_order')}</span>
        <input class="field-entry numeric" type="text" name="manufactured_module[${newModuleId}][sort_order]" value="" size="3">
        </label>
        </div>
        <div class="col-xs-12 col-md-width-auto">
        <div class="padding-medium cursor-pointer top-margin-medium js-remove-manufactured" data-tooltip="${language.get(
          'button_remove'
        )}" data-manufactured-id="${newModuleId}">
        <i class="fas fa-trash text-gray"></i>
        </div>
        </div>
        </div>`;

    MODULE_CONTAINER.id = newModuleId;
    MODULE_CONTAINER.setAttribute(
      'class',
      'background-white padding-large bottom-margin-medium shadow-small adm-focus-within js-manufactured'
    );
    MODULE_CONTAINER.innerHTML = HTML;

    containerManufacturedList.prepend(MODULE_CONTAINER);
    initRemoveManufactured(MODULE_CONTAINER);

    newModuleId++;
  }
});
