<script>
import { storeToRefs } from "pinia";
import { defineComponent, ref } from "vue";

import { apiBack } from "src/boot/axios";
import { quasarNotify } from "src/functions/quasarNotify";
import { useFormStore } from "src/stores/forms";
import * as M from "src/utils/zod/messages";
import IconPostalCode from "../icons/IconPostalCode.vue";

export default defineComponent({
  name: "postal-code",
  components: { IconPostalCode /* IconInfo, */ /* IconSearch */ },
  props: ["modelValue", "bindValue", "setFieldError"],
  setup({ setFieldError, modelValue }, { emit }) {
    const formStore = useFormStore();
    const { postalCodeValid } = storeToRefs(formStore);

    const postalCodeInput = ref(modelValue);

    function updateModel(value) {
      emit("update:modelValue", value);
      postalCodeInput.value = value;
    }

    const isPostalCodeLoading = ref(false);
    async function onBlur() {
      try {
        if (postalCodeInput.value.length < 5) {
          quasarNotify({
            type: "info",
            message: `${M.fiveLength}, Cantidad de caracteres: ${postalCodeInput.value.length}`,
          });
          setFieldError("postalCode", M.fiveLength);
          return;
        }

        isPostalCodeLoading.value = true;

        //TODO - Promesa consultando la api para ver las fechas existentes
        const {
          data: { data },
        } = await apiBack.get(`/delivery/dates`, {
          params: { postalCode: postalCodeInput.value },
        });
        const dates = data.map(({ nextDay }) => {
          const getDate = new Date(nextDay);
          const day = getDate.getDate().toString().padStart(2, "0");
          const month = (getDate.getMonth() + 1).toString().padStart(2, "0");
          const year = getDate.getFullYear();
          const formattedDate = `${year}/${month}/${day}`;

          return formattedDate;
        });

        if(!dates.length) {
          quasarNotify({
            type: "erro",
            message: `No tenemos fechas de entrega posibles para este código postal`,
          });
          setFieldError("postalCode", M.fiveLength);
        }

        postalCodeValid.value.dataOptions = dates;
        postalCodeValid.value.isValid = true;
        isPostalCodeLoading.value = false;
      } catch (error) {
        quasarNotify({
          type: "erro",
          message:
            "Se ha producido un error en el proceso de identificación del código postal",
        });
        isPostalCodeLoading.value = false;
      } finally {

      }
    }

    return { updateModel, onBlur, isPostalCodeLoading };
  },
});
</script>

<template>
  <div class="custom-input-el postal-code">
    <IconPostalCode />

    <div class="custom-block-content">
      <p class="custom-head-paragraph">
        ¿Dónde?
        <!-- <IconInfo /> -->
      </p>

      <q-input
        :model-value="modelValue"
        @update:model-value="updateModel"
        v-bind="bindValue"
        class="custom-main-paragraph field-postal-code"
        :error="false"
        placeholder="código postal"
        mask="#####"
        borderless
        dense
        @blur="onBlur"
      />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.custom-input-el .custom-block-content .search-btn {
  padding: 8px;
  & .q-btn__content {
    & svg {
      width: 14px;
      height: 14px;
    }
  }
}
</style>