<template>
  <q-select
    v-model="selectedCountry"
    v-bind="$attrs"
    use-input
    hide-selected
    fill-input
    clearable
    :options="countryOptions"
    :label="label"
    :loading="loading"
    :placeholder="
      $t('common.actions.search') + ' ' + $t('ui.navigation.country')
    "
    :rules="rules"
    :error
    :error-message
    @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>
  </q-select>
</template>

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

const { label, rules, initialId } = defineProps({
  label: {
    type: String,
    default: () => useI18n().t("ui.navigation.country"),
  },
  rules: {
    type: Array,
    default: () => [],
  },
  initialId: {
    type: Number,
    required: false,
    default: null,
  },
  error: {
    type: Boolean,
    default: false,
  },
  errorMessage: {
    type: String,
    default: "",
  },
});

const selectedCountry = defineModel();

const loading = ref(false);
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 {
    loading.value = true;
    baseCountry.value = await getCountries();
    countryOptions.value = baseCountry.value.map((country) => ({
      label: country.name,
      value: country.id,
    }));
    if (initialId) {
      selectCountryById(initialId);
    }
  } catch (e) {
    console.log(e);
  } finally {
    loading.value = false;
  }
});

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