<template>
  <div class="flex flex-col w-full lg:max-w-4xl mx-auto">
    <slot />

    <UStepper ref="stepper" v-model="activeStepperItemIndex" :items="stepperItems" class="w-full" />

    <h1 v-if="currentFormElementSection?.title" class="text-xl text-pretty font-bold text-highlighted">
      {{ currentFormElementSection.title }}
    </h1>

    <UCard variant="subtle">
      <FormEngine
        v-if="currentFormElementSection?.formElements"
        v-model="currentFormElementSection.formElements"
        :application-form-id="applicationFormId"
        :disabled="disabled"
        @add:input-form="handleAddInputForm"
      />

      <div class="flex gap-2 justify-between mt-4">
        <UButton leading-icon="i-lucide-arrow-left" :disabled="!stepper?.hasPrev" @click="handleNavigate('backward')">
          Prev
        </UButton>

        <UButton
          v-if="stepper?.hasNext"
          trailing-icon="i-lucide-arrow-right"
          :disabled="!stepper?.hasNext"
          @click="handleNavigate('forward')"
        >
          Next
        </UButton>

        <div v-if="!stepper?.hasNext" class="flex flex-wrap items-center gap-1.5">
          <UButton trailing-icon="i-lucide-save" :disabled="disabled" variant="outline" @click="emit('save')">
            Save
          </UButton>
          <UButton trailing-icon="i-lucide-send-horizontal" :disabled="disabled" @click="emit('submit')">
            Submit
          </UButton>
        </div>
      </div>
    </UCard>
  </div>
</template>

<script setup lang="ts">
import type { ApplicationFormDto, FormElementSectionDto } from '~~/.api-client'

const props = defineProps<{
  formElementSections: FormElementSectionDto[]
  initialSectionIndex?: number
  applicationFormId?: string
  disabled?: boolean
}>()

const emit = defineEmits<{
  save: []
  submit: []
  'add-input-form': [updatedForm: ApplicationFormDto | undefined]
  navigate: [{ direction: 'forward' | 'backward'; index: number }]
}>()

const { stepper, activeStepperItemIndex, stepperItems, currentFormElementSection, navigateStepper } = useFormStepper(
  computed(() => props.formElementSections)
)

const { addInputFormToApplicationForm } = useFormElementManagement(currentFormElementSection, props.applicationFormId)

onMounted(() => {
  if (props.initialSectionIndex !== undefined) {
    activeStepperItemIndex.value = props.initialSectionIndex
  }
})

async function handleAddInputForm(position: number) {
  const updatedForm = await addInputFormToApplicationForm(position)
  emit('add-input-form', updatedForm)
}

async function handleNavigate(direction: 'forward' | 'backward') {
  await navigateStepper(direction)
  emit('navigate', { direction, index: activeStepperItemIndex.value })
}
</script>
