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

        <template #right>
          <UTooltip text="Notifications" :shortcuts="['N']">
            <UButton color="neutral" variant="ghost" square>
              <UChip color="error" inset>
                <UIcon name="i-lucide-bell" class="size-5 shrink-0" />
              </UChip>
            </UButton>
          </UTooltip>
        </template>
      </UDashboardNavbar>

      <UDashboardToolbar>
        <template #left />
      </UDashboardToolbar>
    </template>

    <template #body>
      Ampel Status: {{ validationStatus }}
      <UForm class="space-y-4" :state="{}" @submit="onSubmit">
        <FormEngine v-model="formElements" />
        <UButton type="submit">Submit</UButton>
      </UForm>
    </template>
  </UDashboardPanel>
</template>

<script setup lang="ts">
import type { ComplianceStatus, PagedApplicationFormDto } from '~/.api-client'
import { useApplicationFormValidator } from '~/composables/useApplicationFormValidator'
import type { FormElementId } from '~/types/FormElement'

const { getAllApplicationForms } = useApplicationForm()
const { validateFormElements } = useApplicationFormValidator()

const { data } = await useAsyncData<PagedApplicationFormDto>(async () => {
  return await getAllApplicationForms()
})

const formElements = computed({
  get: () => data?.value?.content[0].formElements ?? [],
  set: (val) => {
    if (val && data.value) {
      data.value.content[0].formElements = val
    }
  }
})
const validationStatus = ref<Map<FormElementId, ComplianceStatus> | undefined>()

watch(
  () => formElements,
  (updatedFormElements) => {
    validationStatus.value = validateFormElements(updatedFormElements.value)
  },
  { deep: true }
)

function onSubmit() {
  console.log('Submitted')
}
</script>
