window.addEventListener('load', function() {
  $('#searchForm').on('submit', function(e) {
    const searchKeyword = $("#searchText").val();

    if (!searchKeyword) {
      $('#searchText').attr('disabled', 'disabled');
    }

    return true;
  });

  $('.btn-remove').on('click', function(e) {
    e.preventDefault();

    const itemId = $(this).data('id');
    const jobName = $(this).data('job');

    $modal = $('#remove-job-warning-modal');
    $modal.find('h4.modal-title').text(`Removing name: ${jobName}`);
    $modal.find('#removeBtn').data('id', itemId);
  });

  $('#removeBtn').on('click', function(e) {
    e.preventDefault();
    const itemId = $(this).data('id');
    window.__api__.remove(`/automation_jobs/remove/${itemId}`, itemId);
  });

  var transportProviderInput = $('#transport-provider').select2({
    placeholder: 'Search by Transport Provider name',
    maximumSelectionSize: 1,
    minimumInputLength: 3,
    ajax: {
      url: '/transport_provider/searchTransportProvider',
      type: 'GET',
      dataType: 'json',
      delay: 250,
      data: function (params) {
        const query = {
          name: params.term,
          page: params.page || 1
        }
        return query;
      },
      processResults: function(res, params) {
        const { data, total } = res;
        params.page = params.page || 1;
        return {
          results: data.map(item => ({ id: item.id, text: item.name })),
          pagination: {
            more: (params.page * 20 ) < +total
          }
        };
      }
    },
  });

  $('#search-form').on('submit', function(e) {
    if (transportProviderInput && transportProviderInput.val()) {
      const selectedText = transportProviderInput.select2('data')[0].text;
      $(this).append(`<input type="hidden" name="transport_provider_name" value="${selectedText.trim()}" />`)
    }

    return true;
  });

  addDatePicker('#from_complete');
  addDatePicker('#to_complete');

  $('.select2-container').css('width', '37%');
});