<template>
  <q-input
    ref="inputRef"
    v-model="formattedValue"
    outlined
    :error-message
    :error="!!errorMessageComp"
    :class="disable ? 'no-pointer-events' : ''"
    :label="newLabel"
    :disable
    :readonly
    hide-bottom-space
    no-error-icon
  >
  </q-input>
</template>
<script setup>
import { useCurrencyInput } from "vue-currency-input";
import { computed, watch } from "vue";
import { useI18n } from "vue-i18n";

const model = defineModel();

const { options, disable, readonly, label, error, errorMessage } = defineProps({
  options: {
    type: Object,
    default: () => ({
      locale: "pt-BR",
      currency: "BRL",
      currencyDisplay: "symbol",
      hideCurrencySymbolOnFocus: false,
      hideGroupingSeparatorOnFocus: false,
      hideNegligibleDecimalDigitsOnFocus: false,
      autoDecimalDigits: true,
      useGrouping: true,
      accountingSign: false,
    }),
  },
  disable: {
    type: Boolean,
    default: false,
  },
  readonly: {
    type: Boolean,
    default: false,
  },
  label: {
    type: String,
    default: () => useI18n().t("common.terms.currency"),
  },
  error: {
    type: Boolean,
    default: false,
  },
  errorMessage: {
    type: String,
    default: "",
  },
});

const { inputRef, formattedValue, numberValue, setValue } =
  useCurrencyInput(options);

const errorMessageComp = computed(() => {
  numberValue.value < 0
    ? useI18n().t("validation.rules.value_smaller_than_zero")
    : undefined;

  return errorMessage ? errorMessage : (error ?? void 0);
});

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

watch(
  () => model.value,
  (value) => {
    setValue(value);
  },
);

watch(numberValue, (value) => {
  model.value = value;
});
</script>
