<template>
  <div class="flex flex-col w-full lg:max-w-4xl mx-auto">
    <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="applicationForm && currentFormElementSection?.formElements"
        v-model="currentFormElementSection.formElements"
        :application-form-id="applicationForm.id"
        :disabled="isReadOnly"
        @add:input-form="handleAddInputForm"
      />
      <div class="flex gap-2 justify-between mt-4">
        <UButton leading-icon="i-lucide-arrow-left" :disabled="!stepper?.hasPrev" @click="navigateStepper('backward')">
          Prev
        </UButton>

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

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

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

const props = defineProps<{
  applicationForm: ApplicationFormDto
}>()

const emit = defineEmits<{
  (e: 'update:applicationForm', updatedForm: ApplicationFormDto): void
}>()

const { updateApplicationForm, submitApplicationForm } = useApplicationForm()
const route = useRoute()
const userStore = useUserStore()
const { user } = storeToRefs(userStore)

const toast = useToast()

const isReadOnly = computed(() => {
  return props.applicationForm?.createdBy.keycloakId !== user.value?.keycloakId
})

const { stepper, activeStepperItemIndex, stepperItems, currentFormElementSection, navigateStepper } = useFormStepper(
  computed(() => props.applicationForm?.formElementSections),
  {
    onNavigate: async () => {
      await navigateTo(`/application-forms/${route.params.id}/${activeStepperItemIndex.value}`)
    }
  }
)

const { addInputFormToApplicationForm } = useFormElementManagement(currentFormElementSection, props.applicationForm?.id)

async function handleAddInputForm(position: number) {
  const updatedForm = await addInputFormToApplicationForm(position)
  if (updatedForm) {
    emit('update:applicationForm', updatedForm)
  }
}

onMounted(() => {
  const sectionIndexParam = route.params.sectionIndex
  if (sectionIndexParam) {
    const sectionIndex = parseInt(Array.isArray(sectionIndexParam) ? sectionIndexParam[0]! : sectionIndexParam)
    activeStepperItemIndex.value = !isNaN(sectionIndex) ? sectionIndex : 0
  }
})

async function onSave() {
  if (props.applicationForm) {
    await updateApplicationForm(props.applicationForm.id, props.applicationForm)
    toast.add({ title: 'Success', description: 'Application form saved', color: 'success' })
  }
}

async function onSubmit() {
  if (props.applicationForm) {
    await submitApplicationForm(props.applicationForm.id)
    await navigateTo('/')
    toast.add({ title: 'Success', description: 'Application form submitted', color: 'success' })
  }
}
</script>
