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

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

  let moduleId = 0;

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

  function removeModules(context) {
    context = context || document;
    let removeButtons = context.querySelectorAll('.js-remove-module');
    for (let i = 0; i < removeButtons.length; i++) {
      removeButtons[i].addEventListener('click', function() {
        this.closest('.js-filtro-valor').remove();
        checkDuplicateFields();
      });
    }
  }

  removeModules();

  const MODULES = info.modules;

  for (const key in MODULES) {
    addModule(MODULES[key]);
  }

  function addModule(module = {}) {
    const { position, layout_id, status, sort_order } = module;
    const CONTAINER_MODULE = document.createElement('div');
    const POSITIONS = window.Type_ModulePosition.getEnumList();
    const  LAYOUTS = info.layouts;
    const  STATUS = window.Type_Status.getEnumList();
    const  HTML = `<div class="row x-small-space-xs">
    <div class="col-md">
      <label class="field field-medium">
        <span class="field-label">${window.language.get('entry_layout')}</span>
        <select class="field-entry layout-select" name="futurafiltrovalor_module[${moduleId}][layout_id]">
          ${Object.keys(LAYOUTS)
            .map(
              key =>
                `<option value="${LAYOUTS[key].layout_id}" ${layout_id == LAYOUTS[key].layout_id ? 'selected' : ''}>${
                  LAYOUTS[key].name
                }</option>`
            )
            .join('')}
        </select>
      </label>
    </div>
    <div class="col-md">
      <label class="field field-medium">
        <span class="field-label">${window.language.get('entry_position')}</span>
        <select class="field-entry position-select" name="futurafiltrovalor_module[${moduleId}][position]">
          ${Object.keys(POSITIONS)
            .map(key => `<option value="${key}" ${key == position ? 'selected' : ''}>${POSITIONS[key]}</option>`)
            .join('')}
        </select>
      </label>
    </div>
    <div class="col-md">
      <label class="field field-medium">
        <span class="field-label">${window.language.get('entry_status')}</span>
        <select class="field-entry" name="futurafiltrovalor_module[${moduleId}][status]">
          ${Object.keys(STATUS)
            .map(key => `<option value="${key}" ${status == key ? 'selected' : ''}>${STATUS[key]}</option>`)
            .join('')}
        </select>
      </label>
    </div>
    <div class="col-md-width-auto">
      <label class="field field-medium">
        <span class="field-label">${window.language.get('entry_sort_order')}</span>
        <input class="field-entry mask-number2" type="text" name="futurafiltrovalor_module[${moduleId}][sort_order]"
        value="${typeof sort_order !== 'undefined' ? sort_order : ''}" size="1">
      </label>
    </div>
    <div class="col-xs-12 col-md-width-auto">
        <div class="padding-medium cursor-pointer top-margin-medium js-remove-module" data-tooltip="${window.language.get(
          'button_remove'
        )}" data-manufactured-id="{{ key }}">
          <i class="fas fa-trash text-gray"></i>
        </div>
      </div>
  </div>`;

    CONTAINER_MODULE.setAttribute(
      'class',
      'content-box background-white shadow-small adm-focus-within bottom-margin-medium padding-large js-filtro-valor'
    );
    CONTAINER_MODULE.innerHTML = HTML;
    CONTAINER_MODULE_LIST.prepend(CONTAINER_MODULE);

    removeModules(CONTAINER_MODULE);

    moduleId++;

    const layoutSelects = CONTAINER_MODULE.querySelectorAll('select');
    layoutSelects.forEach(select => {
      select.setAttribute('data-original-value', select.value);
      select.addEventListener('change', checkDuplicateFields);
    });

    function checkDuplicateFields() {
      const modules = document.querySelectorAll('.js-filtro-valor');
      const contentPositions = ['content_top', 'content_bottom', 'column_left'];
      const appPosition = 'content_app';
      let layoutPositionMap = {};
      let errors = false;
  
      modules.forEach(module => {
          const layoutSelect = module.querySelector('.layout-select');
          const positionSelect = module.querySelector('.position-select');
          const layout = layoutSelect.value;
          const position = positionSelect.value;
  
          if (!layoutPositionMap[layout]) {
              layoutPositionMap[layout] = {};
          }
  
          if (contentPositions.includes(position) || position === appPosition) {
              if (!layoutPositionMap[layout][position]) {
                  layoutPositionMap[layout][position] = 0;
              }
              layoutPositionMap[layout][position]++;
          }
      });
  
      modules.forEach(module => {
          const layoutSelect = module.querySelector('.layout-select');
          const positionSelect = module.querySelector('.position-select');
          const layout = layoutSelect.value;
          const position = positionSelect.value;
  
          const contentCount = contentPositions.reduce((count, pos) => {
              return count + (layoutPositionMap[layout][pos] || 0);
          }, 0);
  
          const appCount = layoutPositionMap[layout][appPosition] || 0;
  
          if ((contentCount > 1 && contentPositions.includes(position)) || (appCount > 1 && position === appPosition)) {
              layoutSelect.style.border = '1px solid #8A0F1A';
              positionSelect.style.border = '1px solid #8A0F1A';
              const errorSpan = layoutSelect.nextElementSibling;
              if (!errorSpan || !errorSpan.classList.contains('error-message')) {
                  const errorSpan = document.createElement('span');
                  errorSpan.classList.add('error-message');
                  errorSpan.style.color = '#8A0F1A';
                  errorSpan.style.fontSize = '14px';
                  errorSpan.innerHTML = 'Os campos não podem <br>ser iguais';
                  layoutSelect.parentNode.insertBefore(errorSpan, layoutSelect.nextElementSibling);
              }
              errors = true;
          } else {
              layoutSelect.style.border = '';
              positionSelect.style.border = '';
              const errorSpan = layoutSelect.nextElementSibling;
              if (errorSpan && errorSpan.classList.contains('error-message')) {
                  errorSpan.remove();
              }
          }
      });
  
      return !errors;
    }
  
    checkDuplicateFields();

  }

});
