<script setup lang="ts">
import { defineAsyncComponent, ref, computed, watch } from 'vue'
import { resolveControlOverride } from '@/core/registry/controlOverride'

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

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

// Sync oldValue when record switches (e.g. prev/next navigation)
watch(() => props.record[props.df.fieldname], (v) => {
  oldValue.value = v
})

const finalCanEdit = computed(() => {
  if (!props.canEdit) return false
  if (props.df.read_only === 1) return false
  if (normalize(String(props.df.fieldtype || '')) === 'ReadOnly') return false
  return true
})

function normalize(name: string) {
  return name.replace(/\s+/g, '')
}

function getControlName(fieldtype: string): string {
  const normalized = normalize(fieldtype)
  if (normalized === 'ReadOnly') return 'Data'
  return normalized
}

// Handle value change with plugin trigger
function handleValueChange(newValue: any) {
  const prevValue = oldValue.value
  props.record[props.df.fieldname] = newValue
  oldValue.value = newValue
  
  // Trigger field change plugin
  if (props.ctx?.onFieldChange && newValue !== prevValue) {
    props.ctx.onFieldChange(props.df.fieldname, newValue, prevValue, props.record)
  }
}

// Resolve component once at setup time - entity and fieldtype are stable
// for the lifetime of this instance (entity change rebuilds the entire form).
const _controlName = getControlName(String(props.df.fieldtype || ''))
const _entity = props.ctx?.entity || ''

let Comp: any = null
if (_controlName) {
  if (_entity) {
    try {
      Comp = defineAsyncComponent(async () => {
        const overrideControl = await resolveControlOverride(_entity, _controlName)
        if (overrideControl) return overrideControl
        return import(`./controls/${_controlName}.vue`)
      })
    } catch { }
  }
  if (!Comp) {
    try {
      Comp = defineAsyncComponent(() => import(`./controls/${_controlName}.vue`))
    } catch { }
  }
}
</script>

<template>
  <div class="field-container">
    <component
      :is="Comp"
      v-if="Comp"
      :df="df"
      :record="record"
      :can-edit="finalCanEdit"
      :ctx="ctx"
      :modelValue="record[df.fieldname]"
      @update:modelValue="handleValueChange"
      :disabled="!finalCanEdit"
    />
    <template v-else>
      <span class="field-value">{{ ctx.t('Unsupported field type') }}: {{ df.fieldtype }}</span>
    </template>
    <div v-if="df.description" class="field-description" v-html="ctx.t(df.description)"></div>
  </div>
</template>

<style scoped>
.field-container {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.field-description {
  font-size: 12px;
  color: #6b7280;
  margin-top: 2px;
}
</style>


