<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>

    <template v-if="currentFormElementSection?.formElementSubSections">
      <UCard
        v-for="subsection in currentFormElementSection.formElementSubSections"
        :key="subsection.id"
        variant="subtle"
        class="mb-6"
      >
        <div class="mb-4">
          <h2 class="text-lg font-semibold text-highlighted">{{ subsection.title }}</h2>
          <p v-if="subsection.subtitle" class="text-sm text-dimmed">{{ subsection.subtitle }}</p>
        </div>
        <FormEngine
          v-model="subsection.formElements"
          :application-form-id="applicationFormId"
          :disabled="disabled"
          @add:input-form="(position) => handleAddInputForm(position, subsection.id)"
        />
      </UCard>
    </template>

    <div class="flex gap-2 justify-between">
      <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"
        size="lg"
        @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" size="lg" @click="emit('save')">
          Save
        </UButton>
        <UButton trailing-icon="i-lucide-send-horizontal" :disabled="disabled" size="lg" @click="emit('submit')">
          Submit
        </UButton>
      </div>
    </div>
  </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)
)

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

async function handleAddInputForm(position: number, subsectionId: string) {
  const subsection = props.formElementSections
    .flatMap((section) => section.formElementSubSections)
    .find((sub) => sub.id === subsectionId)

  if (!subsection) {
    return
  }

  const { addFormElementToSubSection } = useFormElementManagement()
  const updatedForm = await addFormElementToSubSection(
    props.applicationFormId,
    subsectionId,
    subsection.formElements,
    position
  )
  emit('add-input-form', updatedForm)
}

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