<template>

  <div class="navbar bg-base-100">
    <div class="basis-1/4 md:basis-1/4">
      <router-link :to="{ name: 'home' }">
        Auburn Oil
      </router-link>
    </div>
    <div class="basis-1/4 md:basis-1/2 justify-center text-center">
      <input type="search" placeholder="Search " class="input input-bordered w-24 md:w-auto" v-model="searchTerm"/>
    </div>
     <SearchResults v-if="customers.length" :customers="customers" />
    <div class="basis-1/2 md:basis-1/4 justify-end gap-5">
          <router-link :to="{ name: 'customerCreate' }">
              <button class="btn">Create Customer</button>
          </router-link>

<!--      <div v-if="employee.id">-->
<!--              <router-link :to="{ name: 'employeeProfile', params: { id: employee.id } }">-->
<!--                  <button class="btn">{{ user.user_name }}</button>-->
<!--            </router-link>-->
<!--      </div>-->
    </div>
  </div>

</template>



<script  lang="ts">

import { debounce } from "vue-debounce";
import SearchResults from "./SearchResults.vue";
import { ref, watch } from "vue";

const searchTerm = ref("");
const customers = ref([]);

const getSearchUrl = () => {
  const url = "https://dummyjson.com/products/search";
  const params = {
    q: searchTerm.value,
    limit: "5",
  };
  const searchParams = new URLSearchParams(params);
  return `${url}?${searchParams}`;
};

const performSearch = debounce(async () => {
  if (searchTerm.value === "") {
    customers.value = [];
    return;
  }
  if (searchTerm.value.length < 2) {
    return;
  }
  const searchUrl = getSearchUrl();
  const response = await (await fetch(searchUrl)).json();

  customers.value = response.products;
}, 600);

watch(searchTerm, () => {
  performSearch();
});
</script>
