<script setup>
import { countries } from "@/utils/countries.js";
import { ref, computed } from "vue";

const props = defineProps({
  modelValue: {
    type: [Object],
    required: true,
  },
});

const emit = defineEmits(["update:modelValue"]);
const componentValue = computed({
  get() {
    return props.modelValue;
  },
  set(value) {
    emit("update:modelValue", value);
  },
});
const toggle = ref(false);

const selectCountry = (country, countryCode) => {
  componentValue.value.country = country;
  componentValue.value.country_code = countryCode;
  toggle.value = false;
};

const filteredCountries = computed(() =>
  countries.filter((country) =>
    country.label
      .toLocaleLowerCase("tr-TR")
      .includes(componentValue.value.country.toLocaleLowerCase("tr-TR")),
  ),
);

const search = () => {
  toggle.value = false;
  if (componentValue.value.country.length >= 3) {
    toggle.value = true;
  }
};
</script>

<template>
  <div class="flex flex-col gap-2">
    <label
      for="country"
      class="block text-sm font-medium text-gray-900 dark:text-white"
    >
      {{ $t("country") }}<span class="text-red-600">*</span>
    </label>
    <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:placeholder-gray-400 dark:text-white dark:focus:ring-primary-500 dark:focus:border-primary-500"
    >
      <input
        id="country"
        v-model="componentValue.country"
        class="text-base text-gray-900 bg-gray-100 !rounded-lg !border-0 block w-full !p-2.5 !min-h-0 !ring-0 !leading-1"
        type="text"
        required
        @keyup="search()"
      />
      <div class="flex items-center pr-2">
        <x-mark-icon
          v-if="toggle"
          class="w-4 h-4 cursor-pointer"
          @click="toggle = false"
        />

        <magnifying-glass-icon v-else class="size-4" />
      </div>
    </div>
    <div class="relative w-full">
      <div
        v-if="filteredCountries.length && toggle"
        class="absolute flex flex-col divide-y-2 w-full bg-white rounded-lg border shadow-lg"
      >
        <div
          v-for="country in filteredCountries"
          :key="country.id"
          class="p-2 hover:bg-gray-50 cursor-pointer text-sm"
          @click="selectCountry(country.label, country.value)"
        >
          {{ country.label }}
        </div>
      </div>
    </div>
  </div>
</template>
