<template>
  <SpaceInput
    v-bind="$props"
    :mask="amountMask"
    :max-length="15"
    :disabled="disabled"
    type="tel"
    @submit="$emit('submit')"
    v-model="amount"
    :numeric="true"
  />
</template>

<script lang="ts">
import { defineComponent, ref, watch, onBeforeMount } from "vue";
import SpaceInput from "./SpaceInput.vue";

export default defineComponent({
  emits: ["update:modelValue"],
  props: {
    modelValue: {
      type: [String, Number, Boolean],
    },
    label: {
      type: String,
    },
    placeholder: {
      type: String,
    },
    error: {
      type: String,
    },
    tooltip: {
      type: String,
    },
    disabled: {
      type: Boolean,
    },
    hasIcon: {
      type: Boolean,
      default: false,
    },
  },
  components: { SpaceInput },
  setup(props, { emit }) {
    const amount: any = ref(null);

    const amountMask = {
      mask: "num",
      blocks: {
        num: {
          mask: Number,
          thousandsSeparator: ",",
          radix: ".",
        },
      },
    };

    watch(
      () => props.modelValue,
      (newVal) => {
        if (newVal !== amount.value) {
          amount.value = newVal ? newVal.toString() : "";
        }
      }
    );

    watch(amount, (newVal: any) => {
      const parsed = parseFloat(newVal);
      emit("update:modelValue", isNaN(parsed) ? "" : parsed);
    });

    onBeforeMount(() => {
      if (props.modelValue) {
        amount.value = props.modelValue;
      }
    });

    return {
      amount,
      amountMask,
    };
  },
});
</script>
