import type { Field } from '@bagelink/vue'
import type { BagelFormState } from '../components/form/useBagelFormState'
import { inject, computed } from 'vue'
import { FORM_STATE_KEY } from '../components/form/useBagelFormState'

export function useFormField<T>(props: {
	field: Field<T>
	fieldID?: string
	modelValue?: any
}) {
	const formState = inject<BagelFormState<T>>(FORM_STATE_KEY)

	const fieldData = computed({
		get: () => {
			if (!props.fieldID || !formState) { return props.modelValue ?? props.field.defaultValue ?? '' }
			const value = formState.getFieldData(props.fieldID)
			// For nested form containers, default to empty object
			if (props.field.$el === 'form' && !value) { return {} }
			// Don't auto-restore defaultValue - let user control their content
			return value ?? ''
		},
		set: (val: any) => {
			if (!props.fieldID || !formState) { return }
			const currentValue = formState.getFieldData(props.fieldID)
			if (JSON.stringify(val) === JSON.stringify(currentValue)) { return }

			if (props.field.onUpdate) {
				props.field.onUpdate(val, currentValue)
			}
			formState.updateField(props.fieldID, val)
		}
	})

	return {
		fieldData,
		formState
	}
}
