<template>
  <div class="titan-form-section space-y-6">
    <component
      v-for="(element, index) in schema"
      :key="`form-element-${index}`"
      :is="getComponent(element.component)"
      v-bind="element.props"
      :model-value="element.model ? modelValue[element.model] : undefined"
      @update:model-value="element.model ? updateField(element.model, $event) : undefined"
    />
  </div>
</template>

<script setup lang="ts">
import type { Component } from 'vue'
import type { FormSectionProps, FormSectionEmits } from '@/types/components'

// Import all components that can be used in schemas
import TitanInput from '@/components/ui/TitanInput.vue'
import TitanTextarea from '@/components/ui/TitanTextarea.vue'
import TitanSelect from '@/components/ui/TitanSelect.vue'
import TitanDatePicker from '@/components/ui/TitanDatePicker.vue'
import TitanImageUpload from '@/components/ui/TitanImageUpload.vue'
import TitanSubheader from '@/components/ui/TitanSubheader.vue'
import TitanButton from '@/components/ui/TitanButton.vue'

// Component registry mapping component names to actual components
const componentRegistry: Record<string, Component> = {
  TitanInput,
  TitanTextarea,
  TitanSelect,
  TitanDatePicker,
  TitanImageUpload,
  TitanSubheader,
  TitanButton,
}

// Props
const props = withDefaults(defineProps<FormSectionProps>(), {
  schema: () => [],
  modelValue: () => ({}),
})

// Emits
const emit = defineEmits<FormSectionEmits>()

/**
 * Gets a component from the registry by name
 * Returns a div as fallback if component is not found
 */
function getComponent(componentName: string): Component | string {
  const component = componentRegistry[componentName]

  if (!component) {
    console.warn(`[TitanFormSection] Component "${componentName}" not found in registry. Available components:`, Object.keys(componentRegistry))
    return 'div'
  }

  return component
}

/**
 * Updates a specific field in the form data
 * and emits the update:modelValue event
 */
function updateField(fieldName: string, value: any) {
  const updatedData = {
    ...props.modelValue,
    [fieldName]: value,
  }
  emit('update:modelValue', updatedData)
}
</script>

<style scoped>
.titan-form-section {
  /* Component-specific styles if needed */
}
</style>
