$(document).ready(function() {
  // Datepicker
  $("#start_date").datepicker({
    defaultDate: "+1w",
    changeMonth: true,
    numberOfMonths: 3,
    format: "yyyy-mm-dd",
    onClose: function(selectedDate) {
      $("#start_date").datepicker("option", "minDate", selectedDate);
    }
  });

  $("#end_date").datepicker({
    defaultDate: "+1w",
    changeMonth: true,
    numberOfMonths: 3,
    format: "yyyy-mm-dd",
    onClose: function(selectedDate) {
      $("#end_date").datepicker("option", "maxDate", selectedDate);
    }
  });

  function loadingButton(btn) {
    if (btn !== null) btn.button("loading");
  }

  function stopLoadingButton(btn) {
    if (btn !== null) btn.button("reset");
  }

  function loadSavedTripsRecord(pageno, filters, btnSearch = null) {
    loadingButton(btnSearch);

    $.ajax({
      url: "/member/loadSavedTripsRecord",
      type: "get",
      dataType: "json",
      data: filters + "&row_no=" + pageno,
      success: function(response) {
        if (response.hasOwnProperty("error")) {
          $("#error-msg").html(response.error);
          $("#print-error-msg").show();
          $("#pagination-saved-trips, #saved-trips-list").hide();
        } else {
          $("#pagination-saved-trips").html(response.pagination);
          createSavedTripsTable(response.result);
          $("#pagination-saved-trips, #saved-trips-list").show();
        }
      },
      complete: function() {
        stopLoadingButton(btnSearch);
      }
    });
  }

  // Load Page Member Account Receipts When Initialize
  loadSavedTripsRecord(0, $("#saved-trips-form").serialize());
  function createSavedTripsTable(result) {
    $("#saved-trips-list tbody").empty();

    for (index in result) {
      let id = result[index].id;
      let member_id = result[index].member_id;
      let trip_name = result[index].trip_name;
      let trip_from = result[index].trip_from;
      let trip_to = result[index].trip_to;
      let country = result[index].country;
      let trip_date = result[index].trip_date;
      let status = result[index].status;
      let added = result[index].added;
      let color = result[index].color;

      let tr = `<tr>
        <td>${id}</td>
        <td>${member_id}</td>
        <td>${trip_name}</td>
        <td>${trip_from}</td>
        <td>${trip_to}</td>
        <td>${country}</td>
        <td>${trip_date}</td>
        <td>${status}</td>
        <td>${added}</td>
        <td>${color}</td>
      </tr>`;

      $("#saved-trips-list tbody").append(tr);
    }
  }

  // Detect pagination click
  $("#pagination-saved-trips").on("click", "a", function(e) {
    e.preventDefault();
    let page_no = $(this).attr("data-ci-pagination-page");

    if (page_no === undefined) {
      return false;
    }

    loadSavedTripsRecord(
      $(this).attr("data-ci-pagination-page"),
      $("#saved-trips-form").serialize()
    );
  });

  // Prevent submit form by press the enter button
  $(window).keydown(function(event) {
    if (event.keyCode == 13) {
      event.preventDefault();

      loadSavedTripsRecord(0, $("#saved-trips-form").serialize());
    }
  });

  function generateSelect2(ele) {
    return $(ele).select2({
      placeholder: "Search by Address",
      maximumSelectionSize: 1,
      minimumInputLength: 3,
      ajax: {
        url: "/member/getLocationByAddress",
        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.address })),
            pagination: {
              more: params.page * 20 < +total
            }
          };
        }
      }
    });
  }

  let start_address = generateSelect2("#start-address");
  let end_address = generateSelect2("#end-address");

  $("#search-saved-trips").on("click", function() {
    const start_address_text = start_address.select2("data").length
      ? start_address.select2("data")[0].text
      : "";
    const end_address_text = end_address.select2("data").length
      ? end_address.select2("data")[0].text
      : "";

    $('input[name="start_address"]').val(start_address_text);
    $('input[name="end_address"]').val(end_address_text);

    loadSavedTripsRecord(0, $("#saved-trips-form").serialize(), $(this));
    return true;
  });

  $("#reset-saved-trips").on("click", function() {
    $("#start-address")
      .val(null)
      .trigger("change");
    $("#end-address")
      .val(null)
      .trigger("change");
    $("#start_date").val(null);
    $("#end_date").val(null);
    $("#country_card").val(null);
  });
});
