<template>
  <DefaultInput
    ref="inputRef"
    v-model="formattedValue"
    v-bind="$attrs"
    :label="label"
    :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 { useInputRules } from "src/composables/useInputRules";

import DefaultInput from "./DefaultInput.vue";

const { inputRules } = useInputRules();

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

const defaultRules = [inputRules.minValue(0)];
const finalRules = ref([]);

const { options, label, rules } = 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: useI18n().t("common.terms.currency"),
  },
  errorMessage: {
    type: String,
    default: "",
  },
  inputClass: {
    type: String,
    default: "",
  },
  rules: {
    type: Array,
    default: () => [],
  },
});

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, ...defaultRules];
  },
);

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