{% extends "layout.html" %} {% block body %}
<h2 class="text-left display-5">Find Worker</h2>

<div class="input mb-3">
  <label for="find_worker" class="form-label"
    >Type to search for a Worker:</label
  >
  <input
    id="find_worker"
    class="form-control"
    type="search"
    placeholder="(preferred) name, email or phone"
    autofocus
  />
</div>
<div class="table-container"></div>

<script src="{{ url_for('static', filename='fuse.js') }}"></script>
<script>
  const endpoint = "/api/workers";

  let state = {
    isSearching: false,
    foundResults: [],
    searchString: "",
  };

  fetch(endpoint)
    .then(response => response.json())
    .catch(function (error) {
      console.log(error);
    })
    .then(function (data) {
      const input = document.querySelector("input");

      input.addEventListener("input", (e) => runSearch(e));

      function runSearch(e) {
        e.preventDefault();
        const searchString = e.currentTarget.value;

        const fuse = new Fuse(data, {
          includeScore: true,
          threshold: 0.5,
          keys: ["name", "preferred_name", "phone", "email"],
        });

        state.searchString = searchString.trim();

        state.foundResults = Array.from(fuse.search(searchString));

        state.isSearching = true;

        dispatch(state);
      }

      function dispatch(state) {
        if (state.isSearching) {
          generateHtml(state);
        }
      }

      function format_contact(type, value) {
        return `<a href="${type}:${value}">${value}</a>`;
      }

      function generateHtml(state) {
        const tableContainer = document.querySelector(".table-container");
        if (!state.searchString) {
          tableContainer.innerHTML = "";
          state.isSearching = false;
          dispatch(state);
        }
        if (!state.foundResults.length && state.searchString !== "") {
          tableContainer.innerHTML = "No results, please refine your search.";
          state.isSearching = false;
          dispatch(state);
        }
        if (state.foundResults.length && state.searchString) {
          state.foundResults = state.foundResults.slice(0, 10);
          const html = `
    <table class="table table-striped table-hover">
      <thead>
        <tr>
          <th style="width: 30%" scope="col">Name</th>
          <th style="width: 30%" scope="col">Department</th>
          <th style="width: 20%" scope="col">Phone</th>
          <th style="width: 20%" scope="col">E-Mail</th>
        </tr>
      </thead>
      <tbody class="table-row">${state.foundResults
        .map(
          ({ item }) => `
            <tr>
            <td scope="row">
              <a href="/worker/${item.id}">
                  ${
                    item.preferred_name
                      ? item.preferred_name + " (" + item.name + ")"
                      : item.name
                  }
              </a></td>
              <td scope="row">
              <a href="/department/${item.department_slug}">${
            item.department_name
          }</a></td>
              <td scope="row">
              ${
                item.phone === null
                  ? "Unknown"
                  : format_contact("tel", item.phone)
              }</td>
              <td scope="row">
              ${
                item.email === null
                  ? "Unknown"
                  : format_contact("mailto", item.email)
              }</td></tr>`
        )
        .join(" ")}
      </tbody>
    </table>`;
          state.foundResults = [];
          state.isSearching = false;
          state.searchString = "";
          return (tableContainer.innerHTML = html);
        }
      }
    });
</script>

{% endblock %}
