<template>
  <UDashboardPanel id="home">
    <template #header>
      <UDashboardNavbar title="Home" :ui="{ right: 'gap-3' }">
        <template #leading>
          <UDashboardSidebarCollapse />
        </template>

        <template #right>
          <UDropdownMenu :items="items">
            <UButton icon="i-lucide-plus" size="md" class="rounded-full" />
          </UDropdownMenu>
        </template>
      </UDashboardNavbar>

      <UDashboardToolbar>
        <UNavigationMenu :items="links" highlight class="-mx-1 flex-1" />
      </UDashboardToolbar>
    </template>

    <template #body>
      <div class="flex flex-col gap-4 sm:gap-6 lg:gap-12 w-full lg:max-w-4xl mx-auto">
        <FormStepperWithNavigation
          :form-element-sections="applicationForm.formElementSections"
          :initial-section-index="sectionIndex"
          :application-form-id="applicationForm.id"
          :disabled="isReadOnly"
          @save="onSave"
          @submit="onSubmit"
          @navigate="handleNavigate"
        >
          <FormValidationIndicator :status="validationStatus" />
        </FormStepperWithNavigation>
      </div>
    </template>
  </UDashboardPanel>
</template>

<script setup lang="ts">
import { ComplianceStatus, type FormElementDto, type FormElementSectionDto } from '~~/.api-client'
import type { FormElementId } from '~~/types/formElement'
import { useApplicationFormValidator } from '~/composables/useApplicationFormValidator'
import { useUserStore } from '~~/stores/useUserStore'

const route = useRoute()
const toast = useToast()

definePageMeta({
  // Prevent whole page from re-rendering when navigating between sections to keep state
  key: (route) => `${route.params.id}`
})

const applicationFormId = Array.isArray(route.params.id) ? route.params.id[0] : route.params.id
const {
  applicationForm,
  navigationLinks: links,
  dropdownItems: items,
  updateApplicationForm
} = await useApplicationFormNavigation(applicationFormId!)

const { updateApplicationForm: updateForm, submitApplicationForm } = useApplicationForm()
const { validateFormElements, getHighestComplianceStatus } = useApplicationFormValidator()
const userStore = useUserStore()
const { user } = storeToRefs(userStore)

const sectionIndex = computed(() => {
  const param = route.params.sectionIndex
  const index = parseInt(Array.isArray(param) ? param[0]! : (param ?? '0'))
  return !isNaN(index) ? index : 0
})

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

const validationMap = ref<Map<FormElementId, ComplianceStatus> | undefined>()
const validationStatus = ref<ComplianceStatus>(ComplianceStatus.NonCritical)

const allFormElements = computed(() => {
  return (
    applicationForm.value?.formElementSections?.flatMap((section: FormElementSectionDto) => section.formElements) ?? []
  )
})

watch(
  () => allFormElements.value,
  (updatedFormElements: FormElementDto[]) => {
    validationMap.value = validateFormElements(updatedFormElements)
    validationStatus.value = getHighestComplianceStatus()
  },
  { deep: true }
)

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

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

async function handleNavigate({ index }: { direction: 'forward' | 'backward'; index: number }) {
  await navigateTo(`/application-forms/${applicationFormId}/${index}`)
}
</script>
