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

        <template #right />
      </UDashboardNavbar>

      <UDashboardToolbar>
        <template #left />
      </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">
        Erstelle Forumular für Organisation: {{ selectedOrganization?.name }}
        <UPageCard title="Ampelstatus" variant="naked" orientation="horizontal" class="mb-4">
          {{ ampelStatusEmoji }}
        </UPageCard>

        <UPageCard variant="subtle">
          <UForm class="space-y-4" :state="{}" @submit="onSubmit">
            <UFormField label="Name">
              <UInput v-if="applicationFormTemplate" v-model="applicationFormTemplate.name" />
            </UFormField>
            <FormEngine v-model="formElements" />
            <UButton type="submit">Submit</UButton>
          </UForm>
        </UPageCard>
      </div>
    </template>
  </UDashboardPanel>
</template>

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

const { getAllApplicationFormTemplates } = useApplicationFormTemplate()
const { createApplicationForm } = useApplicationForm()
const { validateFormElements, getHighestComplianceStatus } = useApplicationFormValidator()
const { user, selectedOrganization } = useAuth()

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

const applicationFormTemplate = computed({
  get: () => data?.value?.content[0] ?? undefined,
  set: (val) => {
    if (val && data.value) {
      data.value.content[0] = val
    }
  }
})

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

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

const ampelStatusEmoji = computed(() => {
  switch (validationStatus.value) {
    case ComplianceStatus.Critical:
      return '🔴'
    case ComplianceStatus.Warning:
      return '🟡'
    case ComplianceStatus.NonCritical:
      return '🟢'
    default:
      return '🟢'
  }
})

async function onSubmit() {
  if (applicationFormTemplate.value) {
    const userDto: UserDto = {
      id: user.value?.id ?? '',
      name: user.value?.name ?? 'Unknown'
    }
    applicationFormTemplate.value.createdBy = userDto
    applicationFormTemplate.value.lastModifiedBy = userDto
    applicationFormTemplate.value.organizationId = selectedOrganization.value?.id ?? ''

    await createApplicationForm(applicationFormTemplate.value)
    await navigateTo('/')
  } else {
    console.error('Application form data is undefined')
  }
}
</script>
