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

const props = defineProps({
  modelValue: Object,
  label: {
    type: String,
    default: "İstisna Sebebi",
  },
});
const emit = defineEmits(["update:modelValue"]);

const exemption_reasons = ref([]);

onMounted(() => {
  exemption_reasons.value = Object.entries(
    window.ginvoice.enums.exemption_reasons,
  ).map(([key, value]) => ({
    value: key,
    text: value,
  }));
});

const internalModel = computed({
  get: () => props.modelValue,
  set: (value) => emit("update:modelValue", value),
});

const searchText = ref("");
const showDropdown = ref(false);

const escapeSpecialRegExCharacters = (value) =>
  value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");

watch(
  () => internalModel.value,
  (newVal) => {
    if (!newVal) {
      searchText.value = "";
      return;
    }

    if (newVal.exemption_reason) {
      searchText.value = newVal.exemption_reason;
    }
  },
  { immediate: true, deep: true },
);

const filteredReasons = computed(() => {
  if (!searchText.value) return exemption_reasons.value;

  const currentValue = internalModel.value?.exemption_reason;
  if (currentValue && searchText.value === currentValue) {
    return exemption_reasons.value;
  }

  const filterRegex = new RegExp(
    escapeSpecialRegExCharacters(searchText.value),
    "i",
  );
  return exemption_reasons.value.filter((reason) =>
    filterRegex.test(reason.text),
  );
});

function selectReason(reason) {
  internalModel.value = {
    ...internalModel.value,
    exemption_code: reason.value,
    exemption_reason: reason.text,
  };
  searchText.value = reason.text;
  showDropdown.value = false;
}

function clearSearch() {
  searchText.value = "";
  internalModel.value = {
    ...internalModel.value,
    exemption_code: "",
    exemption_reason: "",
  };
  showDropdown.value = false;
}

function onSearchInput() {
  if (!internalModel.value.exemption_reason) {
    internalModel.value = {
      ...internalModel.value,
      exemption_code: "",
      exemption_reason: "",
    };
  }
}

function onBlur() {
  setTimeout(() => {
    showDropdown.value = false;
  }, 200);
}
</script>

<template>
  <div class="flex flex-col">
    <label
      for="exemption_reason"
      class="block text-sm font-medium text-gray-800 dark:text-white mb-2"
    >
      {{ label }}
    </label>

    <div class="relative w-full">
      <div
        class="flex items-center bg-gray-100 border border-gray-300 text-gray-900 rounded-lg dark:bg-gray-700 dark:border-gray-600 dark:text-white"
      >
        <input
          id="exemption_reason"
          v-model="searchText"
          type="text"
          class="border-0 bg-transparent ring-0 block w-full p-2.5 text-base text-gray-900 leading-none"
          name="exemption_reason"
          autocomplete="off"
          @focus="showDropdown = true"
          @blur="onBlur"
          @input="onSearchInput"
        />
        <x-mark-icon
          v-if="searchText"
          class="w-4 h-4 mr-2 cursor-pointer"
          @click="clearSearch"
        />
        <magnifying-glass-icon v-else class="w-4 h-4 mr-2" />
      </div>

      <div
        v-if="filteredReasons.length && showDropdown"
        class="absolute z-10 flex flex-col divide-y-2 w-full bg-white rounded-lg border shadow-lg max-h-60 overflow-y-auto"
      >
        <span
          v-for="reason in filteredReasons"
          :key="reason.value"
          class="p-4 hover:bg-gray-50 cursor-pointer text-sm"
          @click="selectReason(reason)"
        >
          {{ reason.text }}
        </span>
      </div>
    </div>
  </div>
</template>
