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

<script setup>
import { computed, watch } from "vue";
import { useCurrencyInput } from "vue-currency-input";

import { useInputRules } from "src/composables/useInputRules";

import DefaultInput from "./DefaultInput.vue";

const { inputRules } = useInputRules();

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

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: "Valor",
  },
  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;
  },
);

const minRule = inputRules.minValue(0);
const finalRules = computed(() => [
  ...rules,
  () => minRule(numberValue.value),
]);
</script>
