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

        <template #right>
          Aktuelle Organisation
          <USelect
            v-model="selectedOrganizationId"
            :items="organizations"
            value-key="id"
            label-key="name"
            size="lg"
            :ui="{
              trailingIcon: 'group-data-[state=open]:rotate-180 transition-transform duration-200'
            }"
            class="w-48"
          />

          <UTooltip text="Notifications" :shortcuts="['N']">
            <UButton color="neutral" variant="ghost" square @click="isNotificationsSlideoverOpen = true">
              <UChip :show="unreadCount > 0" color="error" inset>
                <UIcon name="i-lucide-bell" class="size-5 shrink-0" />
                <span v-if="unreadCount > 0" class="ml-1 text-xs">{{ unreadCount }}</span>
              </UChip>
            </UButton>
          </UTooltip>

          <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">
        <div
          v-for="(applicationFormElem, index) in applicationForms"
          :key="applicationFormElem.id"
          class="flex justify-between items-center p-4 bg-white rounded-lg shadow-md"
          @click="navigateTo(`application-forms/${applicationFormElem.id}/0`)"
        >
          <div>
            <p class="font-medium text-(--ui-text-highlighted) text-base">
              #{{ index }} {{ applicationFormElem.name }}
            </p>
            <p class="text-(--ui-text-muted) text-sm">
              Zuletzt bearbeitet von {{ applicationFormElem.lastModifiedBy.name }} am
              {{ formatDate(applicationFormElem.modifiedAt) }}
            </p>
            <p class="text-(--ui-text-muted) text-sm">
              Erstellt von {{ applicationFormElem.createdBy.name }} am {{ formatDate(applicationFormElem.createdAt) }}
            </p>
            <p class="text-(--ui-text-muted) text-sm">Status: {{ applicationFormElem.status }}</p>
          </div>
          <div>
            <UPageLinks :links="getLinksForApplicationForm(applicationFormElem)" />
          </div>
        </div>
      </div>
    </template>
    <DeleteModal
      v-if="isDeleteModalOpen && applicationFormNameToDelete"
      v-model:is-open="isDeleteModalOpen"
      :application-form-to-delete="applicationFormNameToDelete"
      @delete="deleteApplicationForm($event)"
    />
  </UDashboardPanel>
</template>

<script setup lang="ts">
import type { ApplicationFormDto, PagedApplicationFormDto } from '~/.api-client'
import type { Organization } from '~/types/keycloak'

const { getAllApplicationForms, deleteApplicationFormById } = useApplicationForm()
const route = useRoute()
const userStore = useUserStore()
const { organizations, selectedOrganization } = storeToRefs(userStore)

// Inject notification state from layout
const { isNotificationsSlideoverOpen, unreadCount } = inject('notificationState', {
  isNotificationsSlideoverOpen: ref(false),
  unreadCount: ref(0)
})

const { data } = await useAsyncData<PagedApplicationFormDto>(
  async () => {
    if (!selectedOrganization.value) {
      throw new Error('No organization selected')
    }
    return await getAllApplicationForms(selectedOrganization.value.id)
  },
  { watch: [selectedOrganization] }
)

const isDeleteModalOpen = computed<boolean>({
  get: () => 'delete' in route.query,
  set: (isOpen: boolean) => {
    if (isOpen) return
    navigateTo({ path: route.path, query: {} })
  }
})

const applicationFormNameToDelete = computed(() => {
  return data?.value?.content.find((appForm) => appForm.id === route.query.id)
})

const selectedOrganizationId = computed({
  get() {
    return selectedOrganization.value?.id
  },
  set(item) {
    // TODO: USelect triggers multiple times after single selection
    selectedOrganization.value = organizations.value.find((i: Organization) => i.id === item) ?? null
  }
})

const { canWriteApplicationForms } = usePermissions()

const items = computed(() => [
  [
    {
      label: 'Neuer Mitbestimmungsantrag',
      icon: 'i-lucide-send',
      to: '/create',
      disabled: !canWriteApplicationForms.value
    }
  ]
])

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

function getLinksForApplicationForm(applicationForm: ApplicationFormDto) {
  return [
    {
      label: 'Bearbeiten',
      icon: 'i-lucide-file-pen',
      to: `/application-forms/${applicationForm.id}`,
      disabled: !canWriteApplicationForms.value
    },
    {
      label: 'Löschen',
      icon: 'i-lucide-trash',
      to: `?delete&id=${applicationForm.id}`,
      disabled: !canWriteApplicationForms.value
    }
  ]
}

async function deleteApplicationForm(applicationFormId: string) {
  await deleteApplicationFormById(applicationFormId)
  data.value?.content.splice(
    data.value?.content.findIndex((appForm) => appForm.id === applicationFormId),
    1
  )
  isDeleteModalOpen.value = false
}
</script>
