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

import DefaultInput from "./DefaultInput.vue";

const $q = useQuasar();

const model = defineModel({
  type: [String, Number],
});

const { label } = defineProps({
  label: {
    type: String,
    default: "CEP",
  },
});

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

const loading = ref(true);

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("cepData", data);
        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>
