$(document).ready( function () {
  const token = $('body').data('token');
  const zindex = $('.adm-suspended-side').zIndex() + 1;

  function filterData() {
    let data = {
      selected_sort: $('select[name=\'sort\']').attr('value'),
      filter_product_content: $('select[name=\'filter_product_content\']').attr('value'),
      filter_product: $('input[name=\'filter_product\']').attr('value'),
      filter_description: $('input[name=\'filter_description\']').attr('value'),
      filter_author: $('input[name=\'filter_author\']').attr('value'),
      filter_status: $('select[name=\'filter_status\']').attr('value'),
      filter_date_start: $('input[name=\'filter_date_start\']').attr('value'),
      filter_date_end: $('input[name=\'filter_date_end\']').attr('value')
    };

    $.ajax({
        url: 'index.php?route=catalog/review/validateFilters&token=' + token,
        type: 'GET',
        data,
        dataType: 'json',
        beforeSend: function () {
          $('.success, .warning').remove();
          $('.adm-suspended-side .field-entry-error').removeClass('field-entry-error');
          $('#js-btn-filter').addClass('btn-loading');
          $('#js-btn-filter').attr('disabled', true);
        },
        success: function(json) {

          if (json['error']) {
            json['error'].fields.forEach( error => {
              $('input[name=\'' + error + '\']').addClass('field-entry-error');
            });
            $('.header-box').append('<div class="warning top-margin-medium">' + json['error']['message'] + '</div>');
          }

          if (json['success']) {
            window.location = json['success'];
          } else {
            $('#js-btn-filter').removeClass('btn-loading');
            $('#js-btn-filter').attr('disabled', false);
          }

        },

      }
    );
  }

  let date_config = {
    dateFormat: 'dd/mm/yy',
    closeText: 'Fechar',
    prevText: '&#x3c;Anterior',
    nextText: 'Pr&oacute;ximo&#x3e;',
    currentText: 'Hoje',
    monthNames: [
      'Janeiro',
      'Fevereiro',
      'Mar&ccedil;o',
      'Abril',
      'Maio',
      'Junho',
      'Julho',
      'Agosto',
      'Setembro',
      'Outubro',
      'Novembro',
      'Dezembro',
    ],
    monthNamesShort: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'],
    dayNames: [
      'Domingo',
      'Segunda-feira',
      'Ter&ccedil;a-feira',
      'Quarta-feira',
      'Quinta-feira',
      'Sexta-feira',
      'Sabado',
    ],
    dayNamesShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
    dayNamesMin: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sab'],
    maxDate: 'today',
    beforeShow: function () {
      setTimeout(function(){
        $('.ui-datepicker').css('z-index', zindex);
      }, 0);

    },
  };

  $('#date-start').datepicker(date_config);
  $('#date-end').datepicker(date_config);

  $("input[name='filter_product']").autocomplete({
    delay: 500,
    source: function(request, response) {
      $.ajax({
        url:
          'index.php?route=catalog/review/autocomplete&token=' + token +
          '&filter_product=' + encodeURIComponent(request.term) +
          '&sort=score',
        dataType: 'json',
        success: function(json) {
          response(
            $.map(json, function(item) {
              return {
                label: item.name,
              };
            })
          );
        },
      });
    },
    focus: function(event, ui) {
      return false;
    },
    select: function(event, ui) {
      $("input[name='filter_product']").val(ui.item.label);
      return false;
    },
  });

  $("input[name='filter_product']").data("autocomplete")._resizeMenu = function () {
    var ul = this.menu.element;
    ul.outerWidth(this.element.outerWidth() + 20);
  }

  $('#js-btn-filter').on('click', function (e) {
    e.preventDefault();
    filterData();
  });

  $('#sort').on('change', function (e) {
    filterData();
  });

  $('.js-clean-filter').on('click', function (e) {
    e.preventDefault();
    let selected_sort = $('select[name=\'sort\']').attr('value');
    window.location = 'index.php?route=catalog/review&token=' + token + (selected_sort ? '&selected_sort=' + selected_sort: '');
  });

});