
let allStreets = [];
let isStreetCardView = false;
let streetsDebounceTimer = null;

$(document).ready(async function () {
  const sessionPreferences = sessionStorage.getItem("preferences");
  if(sessionPreferences){
    const preferencesData = await parseJSONData(sessionPreferences);
    preferencesData?.is_card_view==1? isStreetCardView = true:isStreetCardView = false;
  }else {
    const preferences = await asyncGetPreferencesRequestForView({
      get_preferences_for_property_user: true,
      property_id: sessionStorage.getItem("propertyId"),
    });
    if(preferences?.length>0) sessionStorage.setItem("preferences",JSON.stringify(preferences[0])); 
    if(preferences?.length>0 && preferences[0]?.is_card_view==1) isStreetCardView = true;
  }

  window.scrollTo({ top: 0, behavior: "smooth" });

  fetch_streets({
    get_streets_request: true,
    property_id: sessionStorage.getItem("propertyId"),
  });
});

function fetch_streets(data) {
  $.ajax({
    url: "include/property_builder/streets/streets_requests.php",
    type: "post",
    data,
    success: function (resp) {
        if (typeof resp === "string") {
          try {
            resp = JSON.parse(resp);
          } catch (err) {
            console.error("Failed to parse JSON:", err);
            return;
          }
        }
      
        if (resp?.success && Array.isArray(resp?.data)) {
          allStreets = resp.data;
          if (window.innerWidth <= 600){
            createStreetCardView(allStreets);
          }else if(isStreetCardView) createStreetCardView(allStreets);
          else createStreetTableView(allStreets);
        } else {
          console.error("❌ Invalid or unexpected data from server:", resp);
        }
    },
    error: function (xhr) {
      console.error("Error loading streets:", xhr);
    }
  });
}

function searchStreets() {
  if(!isStreetCardView){
    searchTable('streets_data_table', 'searchStreetInput');
    return;
  }
  clearTimeout(streetsDebounceTimer);
  streetsDebounceTimer = setTimeout(() => {
    const searchInput = document.getElementById("searchStreetInput");
    if (!searchInput) {
      console.warn("Search input not found: searchStreetInput");
      return;
    }
    
    const searchValue = searchInput.value.toLowerCase();
    
    // Filter streets data
    let matchedStreets = allStreets.filter(
      (street) =>
        !searchValue ||
        Object.values(street).some(
          (field) => field && field.toString().toLowerCase().includes(searchValue)
        )
    );
    
    // Re-render based on current view
    if (window.innerWidth <= 600 || isStreetCardView) {
      createStreetCardView(matchedStreets);
    } else {
      createStreetTableView(matchedStreets);
    }
  }, 200);
}

function createStreetCardView(data) {
  let html = `<div class="row">`;
  if (data.length === 0) {
    const searchValue = document.getElementById("searchStreetInput")?.value;
    if (searchValue && searchValue.trim() !== "") {
      html += `
        <div class="text-center p-4 w-100">
          <i class="fas fa-info-circle text-muted fa-3x mb-3"></i>
          <h5 class="text-muted">No Streets Found</h5>
          <p class="text-muted">No streets found matching "${searchValue}".</p>
        </div>
      `;
    } else {
      html += `
        <div class="text-center p-4 w-100">
          <i class="fas fa-info-circle text-muted fa-3x mb-3"></i>
          <h5 class="text-muted">No Streets Found</h5>
          <p class="text-muted">There are no streets to display.</p>
        </div>
      `;
    }
  } else {
    data.forEach(street => {
      html += `
        <div class="col-lg-4 col-md-6 col-sm-12 mb-3">
          <div class="card h-100 shadow-sm">
            <div class="card-header d-flex align-items-center">
              <h6 class="mb-0">
                <i class="fas fa-road mr-2"></i>
                ${street.name}
              </h6>
              <div class="ml-auto">
                <i class='fas fa-edit text-primary mx-1 edit-street-btn cursor_pointer' title='Edit Street' data-id='${street.id}'></i>
                <i class='fas fa-trash-alt text-danger mx-1 delete-street-btn cursor_pointer' title='Delete Street' data-id='${street.id}' data-name='${street.name.replace(/"/g, "&quot;")}'></i>
              </div>
            </div>
            <div class="card-body">
              <div class="row">
                <div class="col-12">
                  <p class="mb-2">
                    <strong><i class="fas fa-map-marker-alt text-primary mr-2"></i>Street:</strong>
                    <span class="ml-2">${street.name}</span>
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>`;
    });
  }
  html += `</div>`;
  const streets_display = document.getElementById("streets_display"); 
  streets_display.innerHTML = DOMPurify.sanitize(html);
  bindStreetEvents();
}

function bindStreetEvents() {
  const $container = $("#streets_display");
  $container.off("click", ".edit-street-btn");
  $container.off("click", ".delete-street-btn");

  $container.on("click", ".edit-street-btn", function () {
    const id = $(this).data("id");
    editStreet(id);
  });

  $container.on("click", ".delete-street-btn", function () {
    const id = $(this).data("id");
    const name = $(this).data("name");
    deleteStreet(id, name);
  });
}

function createStreetTableView(data) {
    if ($.fn.DataTable.isDataTable("#streets_data_table")) {
      $("#streets_data_table").DataTable().destroy();
    }
  
    if (data.length === 0) {
      const streets_display = document.getElementById("streets_display");
      streets_display.innerHTML = "<div class='col-12 text-center'><p>No streets found</p></div>";
      return;
    }
    let html = `
      <table id="streets_data_table" class="table table-bordered table-hover text-nowrap" style="width:100%; table-layout:auto;">
        <thead>
          <tr>
            <th>Street</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
    `;
  
    if (data.length === 0) {
      html += `<tr><td colspan="2" class="text-center">No streets found</td></tr>`;
    } else {
      data.forEach(street => {
        html += `
          <tr>
            <td>${street.name}</td>
            <td>
              <i class="fas fa-edit text-primary mx-1 edit-street-btn cursor_pointer" title="Edit" data-id="${street.id}"></i>
              <i class="fas fa-trash-alt text-danger mx-1 delete-street-btn cursor_pointer" title="Delete" data-id="${street.id}" data-name="${street.name.replace(/"/g, "&quot;")}"></i>
            </td>
          </tr>`;
      });
    }
  
    html += `
        </tbody>
      </table>
    `;
  
    const streets_display = document.getElementById("streets_display"); 
    streets_display.innerHTML = DOMPurify.sanitize(html);
  
    $("#streets_data_table").DataTable({
      responsive: true,
      order: [],
      paging: false,
      pageLength: -1,
      searching: false,
    });
    bindStreetEvents();
} 

function editStreet(id) {
    const street = allStreets.find(s => s.id == id);
    if (!street) return;
  
    $("#editstreetid").val(street.id);
    $("#editstreetname").val(street.name);
    $("#origname").val(street.name);
    $("#editstreetsmodal").modal("show");
}

$("#editStreetForm").submit(function (e) {
    e.preventDefault();
  
    const id = $("#editstreetid").val();
    const name = $("#editstreetname").val().trim();
    const origname = $("#origname").val().trim();
  
    if (!id || !name) return;
  
    $.post("include/property_builder/streets/streets_requests.php", {
      edit_street_request: true,
      id: id,
      name: name,
      origname: origname
    }, function (response) {
      if (response.success) {
        $("#editstreetsmodal").modal("hide");
        fetch_streets({
          get_streets_request: true,
          property_id: sessionStorage.getItem("propertyId")
        });
      } else {
        alert(response.message || "Something went wrong");
      }
    }, "json");
});

function deleteStreet(id, name) {
  showConfirmModal("Are you sure you want to delete this street?", function () {
    $.post("/include/property_builder/streets/streets_requests.php", {
      delete_street_request: true,
      id: id,
      name: name
    }, function (response) {
      if (response){
        fetch_streets({
          get_streets_request: true,
          property_id: sessionStorage.getItem("propertyId")
        });
      }
    });
  });
}
