<template>
  <div v-for="formElement in props.modelValue" :key="formElement.id">
    <component
      :is="getResolvedComponent(formElement)"
      :form-options="formElement.options"
      @update:form-options="updateFormOptions($event)"
    />
  </div>
</template>

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

const props = defineProps<{
  modelValue: FormElementDto[]
}>()

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

// TODO: Lazy loading?
function getResolvedComponent(formElement: FormElementDto) {
  switch (formElement.type) {
    case 'CHECKBOX':
    case 'DROPDOWN':
    case 'RADIOBUTTON':
    case 'SWITCH':
      return resolveComponent('TheSwitch')
    case 'TEXTFIELD':
      return resolveComponent('TheInput')
    default:
      return resolveComponent('Unimplemented')
  }
}

function updateFormOptions(formOptions: FormOptionDto[]) {
  const updatedModelValue = [...props.modelValue]
  updatedModelValue[0] = { ...updatedModelValue[0], options: formOptions }
  emit('update:modelValue', updatedModelValue)
}
</script>
