<template>
  <div v-bind="$attrs">
    <q-input
      v-model="model"
      outlined
      debounce="500"
      :disable="disable"
      :class="disable ?? 'no-pointer-events'"
      :readonly="readonly"
      :label="newLabel"
      :mask="masks.Brasil.cep"
      :rules="rules"
      :loading="loading"
      :error
      :error-message
    />
  </div>
</template>
<script setup>
import { watch, computed, ref, nextTick } from "vue";
import { useQuasar } from "quasar";
import masks from "src/helpers/masks.js";

const $q = useQuasar();

const model = defineModel();

const { disable, readonly, label, rules } = defineProps({
  disable: {
    type: Boolean,
    default: false,
  },
  readonly: {
    type: Boolean,
    default: false,
  },
  label: {
    type: String,
    default: "CEP",
  },
  rules: {
    type: Array,
    default: () => [],
  },
  error: {
    type: Boolean,
    default: false,
  },
  errorMessage: {
    type: String,
    default: "",
  },
});

const emit = defineEmits([
  "cidade",
  "estado",
  "rua",
  "bairro",
  "numero",
  "complemento",
  "uf",
]);

const loading = ref(false);

const newLabel = computed(() => label ?? void 0);

watch(
  () => model.value,
  async (value) => {
    if (value < 0) {
      model.value = 0;
    }
    if (value && value.length > 8) {
      try {
        loading.value = true;
        const response = await fetch(`https://viacep.com.br/ws/${value}/json`);
        const data = await response.json();
        emit("estado", data.estado);
        emit("uf", data.uf);
        // this is a hack to work well with the city and state select
        await nextTick();
        emit("cidade", data.localidade);
        emit("rua", data.logradouro);
        emit("bairro", data.bairro);
        emit("numero", null);
        emit("complemento", null);
      } catch (error) {
        console.error(error);
        $q.notify({
          message: "CEP inválido",
          color: "negative",
        });
      } finally {
        loading.value = false;
      }
    }
  },
);
</script>
