<template>
  <DefaultSelect
    v-model="selectedState"
    v-bind="$attrs"
    use-input
    hide-selected
    fill-input
    clearable
    :options="stateOptions"
    :label
    :loading
    :placeholder
    @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 { getStates } from "src/api/state";
import { ref, onMounted, watch } from "vue";
import { normalizeString } from "src/helpers/utils";
import { useI18n } from "vue-i18n";
import DefaultSelect from "src/components/defaults/DefaultSelect.vue";

const emit = defineEmits(["selectedCountryId"]);

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

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

const loading = ref(true);
const baseOptions = ref([]);
const stateOptions = ref([]);

const filterFn = (val, update) => {
  ensureOnlyPossibleOptions(country?.value);
  const needle = normalizeString(val);
  stateOptions.value = stateOptions.value.filter((v) => {
    return (
      normalizeString(v.label).includes(needle) ||
      normalizeString(v.code).includes(needle)
    );
  });
  update();
};

const selectStateById = async (id) => {
  if (selectedState.value?.value === id) return;
  selectedState.value = baseOptions.value.find((state) => state.value === id);
};

const selectStateByName = (name) => {
  if (selectedState.value?.label === name) return;
  selectedState.value = baseOptions.value.find((state) => state.label === name);
};

const selectStateByCode = (code) => {
  if (selectedState.value?.code === code) return;
  selectedState.value = baseOptions.value.find((state) => state.code === code);
};

const ensureOnlyPossibleOptions = (country_id) => {
  if (country_id) {
    stateOptions.value = baseOptions.value.filter(
      (state) => state.country_id === country_id,
    );
  } else {
    stateOptions.value = baseOptions.value;
  }
};

watch(
  () => country,
  (value, oldValue) => {
    if (
      value?.value != oldValue?.value &&
      value?.value != selectedState.value?.country_id
    ) {
      selectedState.value = null;
    }
    if (value) {
      ensureOnlyPossibleOptions(value.value);
    }
  },
  { immediate: true },
);

watch(selectedState, () => {
  if (selectedState.value?.country_id) {
    emit("selectedCountryId", selectedState.value.country_id);
  }
});

onMounted(async () => {
  try {
    const baseStates = await getStates();
    baseOptions.value = baseStates.map((state) => ({
      label: state.name,
      value: state.id,
      code: state.code,
      country_id: state.country_id,
    }));
    stateOptions.value = baseOptions.value;
    if (initialId) {
      selectStateById(initialId);
    }
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
  }
});

defineExpose({
  selectStateById,
  selectStateByName,
  selectStateByCode,
});
</script>
