<template>
  <DefaultSelect
    v-model="selectedCountry"
    v-bind="$attrs"
    use-input
    hide-selected
    fill-input
    clearable
    :label
    :loading
    :placeholder
    :options="countryOptions"
    @filter="filterFn"
  >
    <template #no-option>
      <q-item>
        <q-item-section class="text-grey">
          {{ $t("http.errors.no_records_found") }}
        </q-item-section>
      </q-item>
    </template>
  </DefaultSelect>
</template>

<script setup>
import { getCountries } from "src/api/country";
import { ref, onMounted } from "vue";
import { useI18n } from "vue-i18n";
import DefaultSelect from "src/components/defaults/DefaultSelect.vue";

const { initialId, placeholder } = defineProps({
  initialId: {
    type: Number,
    required: false,
    default: null,
  },
  placeholder: {
    type: String,
    default: () =>
      useI18n().t("common.actions.search") +
      " " +
      useI18n().t("ui.navigation.country"),
  },
  label: {
    type: String,
    default: () => useI18n().t("ui.navigation.country"),
  },
});

const selectedCountry = defineModel({ type: Object });

const loading = ref(true);
const baseCountry = ref([]);
const countries = ref([]);
const countryOptions = ref([]);

const filterFn = async (val, update) => {
  const filter = () => {
    const needle = val.toLowerCase();
    countries.value = baseCountry.value.filter((v) =>
      v.name.toLowerCase().includes(needle),
    );
    countryOptions.value = countries.value.map((country) => ({
      label: country.name,
      value: country.id,
    }));
  };

  update(filter);
};

const selectCountryByName = (name) => {
  if (selectedCountry.value && selectedCountry.value.label === name) return;
  selectedCountry.value = countryOptions.value.find(
    (country) => country.label === name,
  );
};

const selectCountryById = (id) => {
  if (selectedCountry.value && selectedCountry.value.id === id) return;
  selectedCountry.value = countryOptions.value.find(
    (country) => country.value === id,
  );
};

onMounted(async () => {
  try {
    baseCountry.value = await getCountries();
    countryOptions.value = baseCountry.value.map((country) => ({
      label: country.name,
      value: country.id,
    }));
    if (initialId) {
      selectCountryById(initialId);
    }
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
  }
});

defineExpose({
  selectCountryByName,
  selectCountryById,
});
</script>
