<script setup lang="ts">
import { computed } from 'vue'
import InputNumber from 'primevue/inputnumber'
import FieldShell from './FieldShell.vue'
const props = withDefaults(defineProps<{ modelValue: number | null; label: string; unit?: string; availableQuantity?: number; allowNegative?: boolean; inputId?: string; disabled?: boolean; required?: boolean; error?: string; help?: string }>(), { unit: '주', allowNegative: false })
const emit = defineEmits<{ 'update:modelValue': [value: number | null]; blur: [event: FocusEvent] }>()

const exceedsAvailable = computed(() =>
  props.modelValue != null && props.availableQuantity != null && props.modelValue > props.availableQuantity
)
const effectiveError = computed(() => props.error ?? (exceedsAvailable.value ? `가용 수량(${props.availableQuantity} ${props.unit})을 초과했습니다.` : undefined))
const effectiveHelp = computed(() => props.availableQuantity != null ? `가용 ${props.availableQuantity} ${props.unit}` : props.help)
</script>
<template>
  <FieldShell :label="label" :input-id="inputId" :required="required" :error="effectiveError" :help="effectiveHelp" v-slot="field">
    <span class="ks-quantity-field">
      <InputNumber
        :input-id="field.inputId"
        :model-value="modelValue"
        :disabled="disabled"
        :invalid="field.invalid"
        :min="allowNegative ? undefined : 0"
        :min-fraction-digits="0"
        :max-fraction-digits="0"
        :aria-describedby="field.describedBy"
        :aria-required="field.required || undefined"
        @update:model-value="emit('update:modelValue', $event)"
        @blur="emit('blur', $event as unknown as FocusEvent)"
      />
      <span class="ks-quantity-field__unit" aria-hidden="true">{{ props.unit }}</span>
    </span>
  </FieldShell>
</template>
<style scoped>
.ks-quantity-field { display: inline-flex; align-items: center; gap: var(--ks-space-2); }
.ks-quantity-field__unit { color: var(--ks-color-text-muted); font-size: var(--ks-font-caption); font-weight: 600; }
</style>
