<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>
        <template #left> toolbar left </template>
      </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">
        <UPageCard variant="subtle">
          <UForm class="space-y-4" :state="{}" @submit="onSubmit">
            <FormEngine v-if="applicationForm" v-model="applicationForm.formElements" />
            <UButton type="submit">Submit</UButton>
          </UForm>
        </UPageCard>
      </div>
    </template>
  </UDashboardPanel>
</template>

<script setup lang="ts">
import type { ApplicationFormDto } from '~/.api-client'
const { getApplicationFormById, updateApplicationForm } = useApplicationForm()
const route = useRoute()

const items = [
  [
    {
      label: 'Neuer Mitbestimmungsantrag',
      icon: 'i-lucide-send',
      to: '/create'
    }
  ]
]

const { data } = await useAsyncData<ApplicationFormDto>(async () => {
  return await getApplicationFormById(Array.isArray(route.params.id) ? route.params.id[0] : route.params.id)
})

const applicationForm = computed({
  get: () => data?.value,
  set: (val) => {
    if (val && data.value) {
      data.value = val
    }
  }
})

async function onSubmit() {
  if (data?.value) {
    await updateApplicationForm(data.value.id, data.value)
  }
}
</script>
