<template>
  <URadioGroup v-model="modelValue" :items="items" />
</template>

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

const props = defineProps<{
  label?: string
  formOptions: FormOptionDto[]
  allFormElements?: FormElementDto[]
}>()

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

const { isFormOptionVisible } = useFormElementVisibility()

const visibleOptions = computed(() => {
  if (!props.allFormElements) return props.formOptions
  return props.formOptions.filter((opt) => isFormOptionVisible(opt.visibilityConditions, props.allFormElements!))
})

// Auto-clear selected option if it becomes hidden
watchEffect(() => {
  if (!props.allFormElements) return
  const selectedOption = props.formOptions.find((opt) => opt.value === 'true')
  if (!selectedOption) return
  if (!isFormOptionVisible(selectedOption.visibilityConditions, props.allFormElements!)) {
    emit(
      'update:formOptions',
      props.formOptions.map((opt) => ({ ...opt, value: 'false' }))
    )
  }
})

// Our "label" is the "value" of the radio button
const items = computed(() => visibleOptions.value.map((option) => ({ label: option.label, value: option.label })))

const modelValue = computed({
  get: () => props.formOptions.find((option) => option.value === 'true')?.label,
  set: (val) => {
    if (val) {
      const updatedModelValue = [...props.formOptions]
      updatedModelValue.forEach((option) => {
        option.value = option.label === val ? 'true' : 'false'
      })
      emit('update:formOptions', updatedModelValue)
    }
  }
})
</script>
