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 transport_provider = $(this).data('transport-provider-account');

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

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

  $(function() {
    if($('#added, #updated, #used').length) {
      $("#added, #updated, #used").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
          }
        };
      }
    },
  });

  $('#transport-provider').on('select2:select', function (e) {
    var data = e.params.data;
    $('input[name="transport_provider_name"]').val(data.text);
  });

  /** date range picker */
  let datepickerOptions = {
    autoUpdateInput: false,
    locale: {
        format: 'YYYY-MM-DD',
        cancelLabel: 'Clear'
    }
  };

  let dateRangeEl = $('input[name="updated"], input[name="used"]');
  dateRangeEl.daterangepicker(datepickerOptions);

  dateRangeEl.on('apply.daterangepicker', function(ev, picker) {
      $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
  });

  dateRangeEl.on('cancel.daterangepicker', function(ev, picker) {
    $(this).val('');
  });
});