<template>
  <UFormField label="Titel">
    <UInput v-model="title" class="w-full" :disabled="props.disabled" />
  </UFormField>
  <UFormField label="Text">
    <UTextarea v-model="body" class="w-full" autoresize :disabled="props.disabled" />
  </UFormField>
</template>

<script setup lang="ts">
import type { FormOptionDto } from '~~/.api-client'

const props = defineProps<{
  formOptions: FormOptionDto[]
  disabled?: boolean
}>()

const emit = defineEmits<{
  (e: 'update:formOptions', value: FormOptionDto[]): void
}>()

const SEPARATOR = '|||'

const title = computed({
  get: () => {
    const currentValue = props.formOptions[0]?.value ?? ''
    return splitValue(currentValue).title
  },
  set: (newTitle: string) => {
    const firstOption = props.formOptions[0]
    if (firstOption) {
      const currentValue = firstOption.value ?? ''
      const { body: currentBody } = splitValue(currentValue)
      const combinedValue = joinValue(newTitle, currentBody)

      const updatedModelValue = [...props.formOptions]
      updatedModelValue[0] = { ...firstOption, value: combinedValue }
      emit('update:formOptions', updatedModelValue)
    }
  }
})

const body = computed({
  get: () => {
    const currentValue = props.formOptions[0]?.value ?? ''
    return splitValue(currentValue).body
  },
  set: (newBody: string) => {
    const firstOption = props.formOptions[0]
    if (firstOption) {
      const currentValue = firstOption.value ?? ''
      const { title: currentTitle } = splitValue(currentValue)
      const combinedValue = joinValue(currentTitle, newBody)

      const updatedModelValue = [...props.formOptions]
      updatedModelValue[0] = { ...firstOption, value: combinedValue }
      emit('update:formOptions', updatedModelValue)
    }
  }
})

function splitValue(value: string): { title: string; body: string } {
  const parts = value.split(SEPARATOR)
  return {
    title: parts[0] || '',
    body: parts[1] || ''
  }
}
function joinValue(title: string, body: string): string {
  return `${title}${SEPARATOR}${body}`
}
</script>
