window.addEventListener('load', function() {
  $('input[datepicker]').datepicker({
    format: "yyyy-mm-dd",
    autoclose: true
  });

  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
          }
        };
      }
    },
  });

  $('#automation-job-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;
  });
});