<template>
  <DefaultSelect
    v-model="selectedCity"
    v-bind="$attrs"
    use-input
    hide-selected
    fill-input
    clearable
    :options="cityOptions"
    :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 { getCities } from "src/api/city";
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(["selectedStateId"]);

const { state, label, initialId, country, placeholder } = defineProps({
  // This country prop is here for future use, maybe
  country: {
    type: Object,
    required: false,
    default: () => {
      return {
        label: "Brasil",
        value: 1,
      };
    },
  },
  state: {
    type: Object,
    required: false,
    default: null,
  },
  label: {
    type: String,
    default: () => useI18n().t("ui.navigation.city"),
  },
  placeholder: {
    type: String,
    default: () =>
      useI18n().t("common.actions.search") +
      " " +
      useI18n().t("ui.navigation.city"),
  },
  initialId: {
    type: Number,
    required: false,
    default: null,
  },
});

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

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

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

const selectCityByName = (name) => {
  if (selectedCity.value?.label === name) {
    return;
  }
  selectedCity.value = baseOptions.value.find((city) => city.label === name);
};

const selectCityById = (id) => {
  if (selectedCity.value?.value === id) {
    return;
  }
  selectedCity.value = baseOptions.value.find((city) => city.value === id);
};

const ensureOnlyPossibleOptions = (country_id, state_id) => {
  if (state_id) {
    cityOptions.value = baseOptions.value.filter((city) => {
      if (country_id) {
        return city.country_id === country_id && city.state_id === state_id;
      }
      return city.state_id === state_id;
    });
  }
  if (!!state_id && !country_id) {
    cityOptions.value = baseOptions.value;
  }
};

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

watch(selectedCity, () => {
  if (selectedCity.value?.state_id) {
    emit("selectedStateId", selectedCity.value.state_id);
  }
});

onMounted(async () => {
  try {
    const baseCities = await getCities();
    baseOptions.value = baseCities.map((city) => ({
      label: city.name,
      value: city.id,
      state_id: city.state_id,
    }));
    cityOptions.value = baseOptions.value;
    if (initialId) {
      selectCityById(initialId);
    }
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
  }
});

defineExpose({
  selectCityByName,
  selectCityById,
});
</script>
