<template>
  <DefaultInput
    ref="inputRef"
    v-model="formattedValue"
    v-bind="$attrs"
    :label="displayLabel"
    :rules="finalRules"
    :input-class="inputClass"
  />
</template>

<script setup>
import { watch, onBeforeMount, ref } from "vue";
import { useCurrencyInput } from "vue-currency-input";
import { useI18n } from "vue-i18n";

import DefaultInput from "./DefaultInput.vue";

const { t } = useI18n();

const model = defineModel({ type: Number });

const finalRules = ref([]);

const props = defineProps({
  options: {
    type: Object,
    default: () => ({
      locale: "pt-BR",
      currency: "BRL",
      currencyDisplay: "symbol",
      hideCurrencySymbolOnFocus: false,
      hideGroupingSeparatorOnFocus: false,
      hideNegligibleDecimalDigitsOnFocus: false,
      autoDecimalDigits: true,
      useGrouping: true,
      accountingSign: false,
    }),
  },
  label: {
    type: String,
    default: null,
  },
  errorMessage: {
    type: String,
    default: "",
  },
  inputClass: {
    type: String,
    default: "",
  },
  rules: {
    type: Array,
    default: () => [],
  },
});

const displayLabel = props.label ?? t("common.terms.currency");
const { options, rules, inputClass } = props;

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

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

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

watch(
  () => rules,
  (value) => {
    finalRules.value = [...value];
  },
);

onBeforeMount(() => {
  finalRules.value = [...rules];
});
</script>
