<template>
  <q-select
    v-model="selectedCity"
    v-bind="$attrs"
    use-input
    hide-selected
    fill-input
    clearable
    :options="cityOptions"
    :label
    :rules
    :loading
    :placeholder="$t('common.actions.search') + ' ' + $t('ui.navigation.city')"
    :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 { getCities } from "src/api/city";
import { ref, onMounted, watch } from "vue";
import { useI18n } from "vue-i18n";

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

const { state, label, rules, initialId } = 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"),
  },
  rules: {
    type: Array,
    default: () => [],
  },
  initialId: {
    type: Number,
    required: false,
    default: null,
  },
  error: {
    type: Boolean,
    default: false,
  },
  errorMessage: {
    type: String,
    default: "",
  },
});

const selectedCity = defineModel();

const loading = ref(false);
const filteredCities = ref([]);
const baseCities = ref([]);
const cityOptions = ref([]);

const filterFn = async (val, update) => {
  if (!val) {
    cityOptions.value = filteredCities.value.map((city) => ({
      label: city.name,
      value: city.id,
      state_id: city.state_id,
    }));
  } else {
    const needle = val.toLowerCase();
    const cities = filteredCities.value.filter(
      (v) => v.name.toLowerCase().indexOf(needle) > -1,
    );
    cityOptions.value = cities.map((city) => ({
      label: city.name,
      value: city.id,
      state_id: city.state_id,
    }));
  }

  update();
};

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

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

watch(
  () => state,
  (value, oldValue) => {
    if (
      value?.value != oldValue?.value &&
      value?.value != selectedCity.value?.state_id
    ) {
      selectedCity.value = null;
    }
    if (value) {
      filteredCities.value = baseCities.value.filter(
        (city) => city.state_id === value.value,
      );
      cityOptions.value = filteredCities.value.map((city) => ({
        label: city.name,
        value: city.id,
        state_id: city.state_id,
      }));
    } else {
      filteredCities.value = baseCities.value;
      cityOptions.value = baseCities.value.map((city) => ({
        label: city.name,
        value: city.id,
        state_id: city.state_id,
      }));
    }
  },
  { immediate: true },
);

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

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

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