<script setup lang="ts">
import { computed, watch, ref } from 'vue'
import { NInputNumber } from 'naive-ui'

const props = defineProps<{ df: any; record: Record<string, any>; canEdit: boolean; ctx: any; onlyInput?: boolean }>()

// Label layout: vertical or horizontal
const labelLayout = computed(() => props.df.label_layout || 'vertical')

const oldValue = ref(props.record[props.df.fieldname])

// Normalize value: empty string -> null
const normalizedValue = computed({
  get: () => {
    const v = props.record[props.df.fieldname]
    return v === '' || v === undefined ? null : Number(v)
  },
  set: (v: number | null) => {
    props.record[props.df.fieldname] = v
  }
})

// Trigger onFieldChange when value changes
watch(() => props.record[props.df.fieldname], (newValue) => {
  if (props.ctx?.onFieldChange && newValue !== oldValue.value) {
    props.ctx.onFieldChange(props.df.fieldname, newValue, oldValue.value, props.record)
  }
  oldValue.value = newValue
})
</script>

<template>
  <div v-if="!onlyInput" :class="['field-wrapper', `layout-${labelLayout}`]">
    <label class="field-label">
      {{ ctx.t(df.label || df.fieldname) }}
      <span v-if="df.reqd" class="required">*</span>
    </label>
    <n-input-number 
      v-model:value="normalizedValue" 
      :precision="2"
      placeholder=""
      :disabled="!canEdit"
    />
  </div>
  <n-input-number 
    v-else
    v-model:value="normalizedValue" 
    :precision="2"
    placeholder=""
    :disabled="!canEdit"
    style="width: 100%"
  />
</template>

<style scoped>
.field-wrapper :deep(.n-input-number) {
  flex: 1;
}
</style>


