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

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

const labelLayout = computed(() => props.df.label_layout || 'vertical')
const showPicker = ref(false)

const dateValue = computed({
  get() {
    const val = props.record[props.df.fieldname]
    if (!val) return null
    if (typeof val === 'number') return val
    // Parse date string as local date (not UTC)
    const parts = String(val).split('-')
    if (parts.length === 3) {
      const year = parseInt(parts[0], 10)
      const month = parseInt(parts[1], 10) - 1
      const day = parseInt(parts[2], 10)
      return new Date(year, month, day).getTime()
    }
    const timestamp = new Date(val).getTime()
    return isNaN(timestamp) ? null : timestamp
  },
  set(newVal: number | null) {
    if (newVal === null) {
      props.record[props.df.fieldname] = null
    } else {
      // Use local date methods to avoid timezone offset
      const date = new Date(newVal)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      props.record[props.df.fieldname] = `${year}-${month}-${day}`
    }
    showPicker.value = false
  }
})

onMounted(() => {
  if (props.onlyInput) {
    nextTick(() => {
      showPicker.value = true
    })
  }
})
</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-date-picker 
      v-model:value="dateValue" 
      type="date"
      placeholder=""
      :disabled="!canEdit"
    />
  </div>
  <div v-else class="date-inline-wrapper">
    <n-date-picker 
      v-model:value="dateValue"
      v-model:show="showPicker"
      type="date"
      placeholder=""
      :disabled="!canEdit"
      style="width: 100%"
    />
  </div>
</template>

<style scoped>
.field-wrapper :deep(.n-date-picker) {
  flex: 1;
}
.date-inline-wrapper :deep(.n-date-picker .n-input__prefix),
.date-inline-wrapper :deep(.n-date-picker .n-input__suffix) {
  display: none !important;
}
</style>


