<template>
  <UCheckboxGroup 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<{
  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 hidden options that are still selected
watchEffect(() => {
  if (!props.allFormElements) return
  const hiddenSelected = props.formOptions.filter(
    (opt) => opt.value === 'true' && !isFormOptionVisible(opt.visibilityConditions, props.allFormElements!)
  )
  if (hiddenSelected.length === 0) return
  emit(
    'update:formOptions',
    props.formOptions.map((opt) => (hiddenSelected.includes(opt) ? { ...opt, value: 'false' } : opt))
  )
})

const items = computed(() => visibleOptions.value.map((option) => ({ label: option.label, value: option.label })))

const modelValue = computed({
  get: () => props.formOptions.filter((option) => option.value === 'true').map((option) => option.label),
  set: (selectedLabels: string[]) => {
    const updatedModelValue = props.formOptions.map((option) => ({
      ...option,
      value: selectedLabels.includes(option.label) ? 'true' : 'false'
    }))
    emit('update:formOptions', updatedModelValue)
  }
})
</script>
