<script setup lang="ts">
import {ref, watch, shallowRef, type PropType, reactive} from 'vue';

const modelValue = defineModel<Boolean>({ required: true });

const props = defineProps({
  checkBoxForm: {
    type: Object as PropType<{
      checkBoxField: {label: string},
      fields: {
        label: string;
        component: any;
        value: any;
        disabled: boolean;
        props?: Record<string, any>;
        title?: string;
        min: number;
      }[];
    }>,
    required: true
  }
});

// Emit setup for nested fields
const emit = defineEmits<{
  (e: 'checkbox-conditional-update', payload: { field: string; value: any }): void
}>();

// Handle checkbox changes
watch(modelValue, (newValue) => {
  if (!newValue) {
    const fields = props.checkBoxForm.fields;
    fields.forEach(field => {
      emit('checkbox-conditional-update', { field, value: null });
    });
  }
});

function handleFieldUpdate(key: string, value: any) {
  emit('checkbox-conditional-update', { key, value });
}
</script>

<template>
  <!-- Checkbox to toggle nested fields -->
  <v-checkbox
      :label="props.checkBoxForm.checkBoxField.label"
      v-model="modelValue"
  ></v-checkbox>

  <!-- Dynamically render nested fields -->
  <template v-for="(field, key) in props.checkBoxForm.fields" :key="key">
    <component
        :is="field.component"
        :label="field.label"
        :title="field.title || ''"
        :disabled="!modelValue"
        :density="'compact'"
        :min="field.min"
        :active="true"
        v-bind="field.props || {}"
        v-model="field.value"
        @update:model-value="handleFieldUpdate(key, field.value)"
        rows="2"
        item-title="type_name"
        hide-details="auto"
        class="mb-2"
        clearable
    />
  </template>
</template>

<style scoped></style>
