<template>
  <template
    v-for="(formElementItem, visibleIndex) in visibleFormElements"
    :key="getElementKey(formElementItem.formElement, formElementItem.indexInSubsection)"
  >
    <div class="group flex py-3 lg:py-4">
      <div class="flex-auto min-w-0">
        <p v-if="formElementItem.formElement.title" class="font-semibold">{{ formElementItem.formElement.title }}</p>
        <p v-if="formElementItem.formElement.description" class="text-dimmed pb-3">
          {{ formElementItem.formElement.description }}
        </p>
        <component
          :is="getResolvedComponent(formElementItem.formElement)"
          :form-options="formElementItem.formElement.options"
          :disabled="props.disabled"
          :all-form-elements="props.allFormElements"
          :table-row-preset="formElementItem.formElement.tableRowPreset"
          @update:form-options="updateFormOptions($event, formElementItem)"
        />
        <div v-if="formElementItem.formElement.isClonable && !props.disabled" class="mt-3">
          <UButton
            variant="outline"
            size="sm"
            leading-icon="i-lucide-copy-plus"
            @click="handleCloneElement(formElementItem.formElement, formElementItem.indexInSubsection)"
          >
            {{ $t('applicationForms.formElements.addAnother') }}
          </UButton>
        </div>
        <TheComment
          v-if="
            applicationFormId && formElementItem.formElement.id && activeFormElement === formElementItem.formElement.id
          "
          :form-element-id="formElementItem.formElement.id"
          :application-form-id="applicationFormId"
          :comments="comments?.[formElementItem.formElement.id]"
          :total-count="
            commentCounts?.[formElementItem.formElement.id] ?? comments?.[formElementItem.formElement.id]?.length ?? 0
          "
          @close="activeFormElement = ''"
        />
      </div>
      <div class="flex items-start gap-1">
        <div class="min-w-9">
          <UButton
            v-if="
              applicationFormId &&
              formElementItem.formElement.id &&
              (commentCounts?.[formElementItem.formElement.id] ?? 0) > 0
            "
            color="neutral"
            variant="soft"
            size="xs"
            icon="i-lucide-message-square"
            class="w-full justify-center"
            @click="toggleComments(formElementItem.formElement.id)"
          >
            {{ commentCounts?.[formElementItem.formElement.id] ?? 0 }}
          </UButton>
        </div>
        <div
          :class="[
            'transition-opacity duration-200',
            openDropdownId === getElementKey(formElementItem.formElement, formElementItem.indexInSubsection)
              ? 'opacity-100'
              : 'opacity-100 lg:opacity-0 lg:group-hover:opacity-100 lg:focus-within:opacity-100'
          ]"
        >
          <UDropdownMenu
            :items="
              getDropdownItems(
                formElementItem.formElement,
                getElementKey(formElementItem.formElement, formElementItem.indexInSubsection),
                formElementItem.indexInSubsection
              )
            "
            :content="{ align: 'end' }"
            @update:open="
              (isOpen: boolean) =>
                handleDropdownToggle(
                  getElementKey(formElementItem.formElement, formElementItem.indexInSubsection),
                  isOpen
                )
            "
          >
            <UButton icon="i-lucide-ellipsis-vertical" color="neutral" variant="ghost" />
          </UDropdownMenu>
        </div>
      </div>
    </div>
    <USeparator v-if="visibleIndex < visibleFormElements.length - 1" />
  </template>
</template>

<script setup lang="ts">
import type { FormElementDto, FormOptionDto } from '~~/.api-client'
import { resolveComponent } from 'vue'
import TheComment from '~/components/TheComment.vue'
import type { DropdownMenuItem } from '@nuxt/ui'
import { useCommentStore } from '~~/stores/useCommentStore'

const props = defineProps<{
  modelValue: FormElementDto[]
  visibilityMap: Map<string, boolean>
  applicationFormId?: string
  disabled?: boolean
  allFormElements?: FormElementDto[]
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', formElementDto: FormElementDto[]): void
  (e: 'click:comments', formElementId: string): void
  (e: 'add:input-form', position: number): void
  (e: 'clone:element', element: FormElementDto, position: number): void
}>()

const commentStore = useCommentStore()
const { loadInitial: loadCommentsInitial } = commentStore
const { commentsByApplicationFormId, countsByApplicationFormId } = storeToRefs(commentStore)

const comments = computed(() => {
  if (!props.applicationFormId) return {}
  return commentsByApplicationFormId.value[props.applicationFormId] ?? {}
})

const commentCounts = computed(() => {
  if (!props.applicationFormId) return {}
  return countsByApplicationFormId.value[props.applicationFormId] ?? {}
})

const route = useRoute()
const activeFormElement = ref('')
const openDropdownId = ref<string | null>(null)

type VisibleFormElement = { formElement: FormElementDto; indexInSubsection: number }

function getElementKey(formElement: FormElementDto, indexInSubsection: number): string {
  return formElement.id || formElement.reference || `element-${indexInSubsection}`
}

const visibleFormElements = computed<VisibleFormElement[]>(() => {
  return props.modelValue
    .map((formElement, indexInSubsection) => ({ formElement, indexInSubsection }))
    .filter(({ formElement }) => {
      const key = formElement.id || formElement.reference
      return key ? props.visibilityMap.get(key) !== false : true
    })
})

function handleDropdownToggle(formElementId: string, isOpen: boolean) {
  openDropdownId.value = isOpen ? formElementId : null
}

function getResolvedComponent(formElement: FormElementDto) {
  switch (formElement.type) {
    case 'CHECKBOX':
      return resolveComponent('TheCheckbox')
    case 'SELECT':
      return resolveComponent('TheSelect')
    case 'RADIOBUTTON':
      return resolveComponent('TheRadioGroup')
    case 'SWITCH':
      return resolveComponent('TheSwitch')
    case 'TEXTFIELD':
      return resolveComponent('TheInput')
    case 'TEXTAREA':
      return resolveComponent('TheTextarea')
    case 'RICH_TEXT':
      return resolveComponent('TheEditor')
    case 'DATE':
      return resolveComponent('TheDate')
    case 'TABLE':
      return resolveComponent('TheTable')
    default:
      return resolveComponent('Unimplemented')
  }
}

function getDropdownItems(
  formElement: FormElementDto,
  formElementKey: string,
  formElementPosition: number
): DropdownMenuItem[] {
  const { t: $t } = useI18n()
  const items = []

  if (route.path !== '/create') {
    items.push({
      label: $t('applicationForms.formElements.comments'),
      icon: 'i-lucide-message-square-more',
      onClick: () => toggleComments(formElement.id ?? formElementKey)
    })
  }

  items.push({
    label: $t('applicationForms.formElements.addInputBelow'),
    icon: 'i-lucide-list-plus',
    onClick: () => emit('add:input-form', formElementPosition)
  })

  return [items]
}

function updateFormOptions(formOptions: FormOptionDto[], target: VisibleFormElement) {
  const targetElement = target.formElement
  const targetIndex = target.indexInSubsection

  const updatedModelValue = props.modelValue.map((element) => {
    if (targetElement.id && element.id === targetElement.id) {
      return { ...element, options: formOptions }
    }
    if (targetElement.reference && element.reference === targetElement.reference) {
      return { ...element, options: formOptions }
    }
    // Newly added form input element
    if (!targetElement.id && !targetElement.reference && props.modelValue[targetIndex] === element) {
      return { ...element, options: formOptions }
    }
    return element
  })
  emit('update:modelValue', updatedModelValue)
}

async function toggleComments(formElementId: string) {
  if (activeFormElement.value === formElementId) {
    activeFormElement.value = ''
    return
  }
  activeFormElement.value = formElementId
  if (props.applicationFormId) {
    await loadCommentsInitial(props.applicationFormId, formElementId)
  }
  emit('click:comments', formElementId)
}

function handleCloneElement(formElement: FormElementDto, position: number) {
  emit('clone:element', formElement, position)
}
</script>
