<script setup>
import {ref, watch} from "vue";
import useDetectOutsideClick from "../../../composables/useDetectOutsideClick.js";
import useDebounce from "../../../composables/useDebounce.js";

const props = defineProps({
  error: {
    type: String,
    required: false,
    default: undefined
  }
});

const errorMessage = ref(props.error)

const alreadyExists = ref(null)

const model = defineModel()
const showAutocomplete = ref(false)
const autocomplete = ref(null)
const results = ref([])

const emit = defineEmits(['update:modelValue', 'variantSelected'])

useDetectOutsideClick(autocomplete, () => {
  if (showAutocomplete.value === true) {
    showAutocomplete.value = false
  }
})

const timer = ref(null)

const maybeShowAutocomplete = (value) => {
  if (!value || value.length <= 2) {
    showAutocomplete.value = false;
    return;
  }

  if (results.value.some(r => r.sku === value)) {
    showAutocomplete.value = false; // Prevent re-opening if the value was selected
    return;
  }

  if (timer.value) {
    clearTimeout(timer.value);
  }

  timer.value = setTimeout(() => {
    search(value);
  }, 300);
};

const search = async (sku) => {
  console.log('search for', sku)

  const response = await fetch(`${window.daylight.apiBase}/variants/search`, {
    method: 'POST',
    body: JSON.stringify({
      searchQuery: sku
    }),
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
    },
  }).then(res => {
    if (!res.ok) {
      throw new Error('Network response was not ok');
    }

    return res.json();
  });

  console.log('response', response)

  if (response.exactMatch) {
    selectOption(response.exactMatch)

    return
  }

  // if (response.alreadyExists) {
  //   alreadyExists.value = response.alreadyExists
  //   return
  // }

  results.value = response.variants

  if (results.value.length > 0) {
    showAutocomplete.value = true
  }
}

const selectOption = (result) => {
  document.dispatchEvent(new CustomEvent('variant-selected', {
    detail: [{
      variant: result
    }]
  }));

  emit('update:modelValue', result.sku);
  emit('variantSelected', result)
}

watch(model, (value) => {
  errorMessage.value = null
  maybeShowAutocomplete(value)
})
</script>

<template>
  <div>
    <div class="relative" :ref="autocomplete">
      <input
          v-model="model"
          class="text-sm border border-gray-400 w-full h-10 rounded-md pr-7"
          type="text"
          :placeholder="__('daylight::store.enter_sku')"
          :class="{ 'border-red-500': errorMessage }"
      />

      <div v-if="errorMessage" class="absolute top-3 right-3 text-red-600">
        <svg class="w-4 h-4" data-slot="icon" fill="none" stroke-width="1.5" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
          <path stroke-linecap="round" stroke-linejoin="round" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126ZM12 15.75h.007v.008H12v-.008Z"></path>
        </svg>
      </div>

      <div class="absolute top-10 border bg-white z-50 h-64 rounded w-[300px] overflow-scroll" v-if="showAutocomplete">
        <ul>
          <li v-for="result in results">
            <a href="#" @click.prevent="selectOption(result)" class="flex w-full p-3 hover:bg-gray-100 truncate whitespace-nowrap">
              <div class="w-12 flex-0 min-w-12">
                <div v-if="!result.image" class="w-10 h-10 flex items-center justify-center text-gray-500 rounded border mr-1 bg-gray-100">
                  <svg class="w-4 h-4" data-slot="icon" fill="none" stroke-width="1.5" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                    <path stroke-linecap="round" stroke-linejoin="round" d="m2.25 15.75 5.159-5.159a2.25 2.25 0 0 1 3.182 0l5.159 5.159m-1.5-1.5 1.409-1.409a2.25 2.25 0 0 1 3.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 0 0 1.5-1.5V6a1.5 1.5 0 0 0-1.5-1.5H3.75A1.5 1.5 0 0 0 2.25 6v12a1.5 1.5 0 0 0 1.5 1.5Zm10.5-11.25h.008v.008h-.008V8.25Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z"></path>
                  </svg>
                </div>
                <img v-else :src="result.image" :alt="result.name" class="object-cover w-10 h-10 rounded border mr-1">
              </div>
              <div class="flex-0 truncate">
                <p class="text-sm">{{ result.sku }}</p>
                <p class="text-xs opacity-50 truncate">{{ result.name }}</p>
              </div>
            </a>
          </li>
        </ul>
      </div>
    </div>

    <div v-if="errorMessage" class="text-sm text-red-600 mt-1">
      {{ errorMessage }}
    </div>

    <div v-if="alreadyExists" class="text-sm text-red-600 mt-1">
      {{ __('daylight::store.sku_already_in_use') }}
    </div>
  </div>
</template>
