<script setup lang="ts">
import type { HTMLAttributes } from 'vue';
import { computed } from 'vue';
import { Input } from '@/components/ui/input';

const props = defineProps<{
    id?: string;
    modelValue?: string | number;
    class?: HTMLAttributes['class'];
    placeholder?: string;
    disabled?: boolean;
}>();

const emit = defineEmits<{
    (event: 'update:modelValue', value: string): void;
}>();

function formatNumber(value: string | number): string {
    const str = String(value ?? '').trim();
    const clean = str.replace(/\D/g, '');

    if (!clean) {
        return '';
    }

    return Number(clean).toLocaleString('id-ID');
}

function parseNumber(value: string): string {
    return value.replace(/\D/g, '');
}

const displayValue = computed({
    get: () => formatNumber(props.modelValue ?? ''),
    set: (value: string) => {
        emit('update:modelValue', parseNumber(value));
    },
});
</script>

<template>
    <Input :id="id" v-model="displayValue" inputmode="numeric" autocomplete="off" :placeholder="placeholder ?? '0'"
        :disabled="disabled" :class="props.class" />
</template>
