<template>
  <div>
    <input
      type="search"
      :value="`${model?.name || ''}`"
      placeholder="Начните вводить название товара..."
      class="form-control"
      ref="inputRef"
    />
  </div>
</template>

<script setup>
import {onMounted, onUnmounted, ref} from "vue";

const model = defineModel();
const inputRef = ref(null);

onMounted(() => {
  const input = inputRef.value;
  if (!input) {
    return;
  }

  $(input).autocomplete({
    'source': function (request, response) {
      if ($(input).val().length === 0) {
        $(input).val(null);
      }

      $.ajax({
        url: `index.php?route=catalog/product/autocomplete&user_token=${window.TeleCart.user_token}&filter_name=` + encodeURIComponent(request),
        dataType: 'json',
        success: function (json) {
          response($.map(json, function (item) {
            return {
              label: item['name'],
              value: item['product_id']
            }
          }));
        }
      });
    },
    'select': function (item) {
      model.value = {
        product_id: Number(item['value']),
        name: item['label'],
      };
    }
  });
});

onUnmounted(() => {
  const input = inputRef.value;
  if (!input) {
    return;
  }

  $(input).autocomplete('destroy');
});
</script>

<style scoped>

</style>
