<template>
  <div
    :class="attrs.class"
    :style="attrs.style"
  >
    <DefaultSelect
      v-model="selectedState"
      v-bind="selectAttrs"
      class="full-width"
      clearable
      fill-input
      hide-selected
      stack-label
      use-input
      :label="label"
      :loading="loading"
      :options="stateOptions"
      :placeholder="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>
  </div>
</template>

<script setup>
import {
  computed,
  onMounted,
  ref,
  useAttrs,
  watch,
} from "vue";

import { getStates } from "src/api/state";
import { normalizeString } from "src/helpers/utils";
import { useI18n } from "vue-i18n";

import DefaultSelect from "src/components/defaults/DefaultSelect.vue";

defineOptions({
  inheritAttrs: false,
});

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

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

const attrs = useAttrs();

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

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

const selectAttrs = computed(() => {
  const {
    // eslint-disable-next-line no-unused-vars
    class: _,
    // eslint-disable-next-line no-unused-vars
    style: __,
    ...rest
  } = attrs;

  return rest;
});

const ensureOnlyPossibleOptions = (countryId) => {
  if (!countryId) {
    stateOptions.value = baseOptions.value;

    return;
  }

  stateOptions.value = baseOptions.value.filter(
    (state) => state.country_id === countryId,
  );
};

const filterFn = (value, update) => {
  update(() => {
    ensureOnlyPossibleOptions(country?.value);

    const needle = normalizeString(value);

    stateOptions.value = stateOptions.value.filter(
      (state) =>
        normalizeString(state.label).includes(needle) ||
        normalizeString(state.code ?? "").includes(needle),
    );
  });
};

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

  selectedState.value =
    baseOptions.value.find(
      (state) => state.code === code,
    ) ?? null;
};

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

  selectedState.value =
    baseOptions.value.find(
      (state) => state.value === id,
    ) ?? null;
};

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

  selectedState.value =
    baseOptions.value.find(
      (state) => state.label === name,
    ) ?? null;
};

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

    ensureOnlyPossibleOptions(value?.value);
  },
  {
    immediate: true,
  },
);

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

onMounted(async () => {
  try {
    const states = await getStates();

    baseOptions.value = states.map((state) => ({
      code: state.code,
      country_id: state.country_id,
      label: state.name,
      value: state.id,
    }));

    ensureOnlyPossibleOptions(country?.value);

    if (initialId) {
      selectStateById(initialId);
    }
  } catch (error) {
    console.error(error);
  } finally {
    loading.value = false;
  }
});

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

<style scoped>
div {
  min-width: 0;
}

:deep(.q-field) {
  min-width: 0;
  width: 100%;
}
</style>