<template>
  <template v-for="(formElement, index) in props.modelValue" :key="formElement.id">
    <div class="group py-3 lg:py-4">
      <div class="flex justify-between">
        <component
          :is="getResolvedComponent(formElement)"
          :form-options="formElement.options"
          :disabled="props.disabled"
          @update:form-options="updateFormOptions($event, index)"
        />
        <UIcon
          name="i-lucide-message-square-more"
          class="size-5 cursor-pointer hidden group-hover:block"
          @click="toggleComments(formElement.id)"
        />
      </div>
    </div>
    <template v-if="applicationFormId && activeFormElement === formElement.id">
      <template v-if="comments?.[formElement.id] && comments[formElement.id].length > 0">
        <UChatMessages :auto-scroll="false" :should-scroll-to-bottom="false">
          <UChatMessage
            v-for="comment in comments[formElement.id]"
            :id="comment.id"
            :key="comment.id"
            :avatar="{ icon: 'i-lucide-bot' }"
            :content="comment.message"
            role="user"
            :side="isCommentByUser(comment) ? 'right' : 'left'"
            variant="subtle"
            :actions="createChatMessageActions(comment)"
          >
            <template #leading="{ avatar }">
              <div class="flex flex-col">
                <UAvatar icon="i-lucide-bot" />
                <p class="text-sm">{{ comment.createdBy.name }}</p>
              </div>
            </template>
          </UChatMessage>
        </UChatMessages>
      </template>
      <UTextarea v-model="commentTextAreaValue" class="w-full" />
      <UButton v-if="!isEditingComment" class="my-3 lg:my-4" @click="submitComment(formElement.id)"> Submit </UButton>
      <UButton v-if="isEditingComment" class="my-3 lg:my-4" @click="updateEditComment"> Edit comment </UButton>
      <UButton v-if="isEditingComment" class="my-3 lg:my-4" @click="cancelEditComment"> Cancel </UButton>
    </template>
    <USeparator />
  </template>
</template>

<script setup lang="ts">
import type { FormElementDto, FormOptionDto } from '~/.api-client'
import { useComment } from '~/composables/comment/useComment'
import { resolveComponent } from 'vue'

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

const emit = defineEmits<{
  (e: 'update:modelValue', formElementDto: FormElementDto[]): void
  (e: 'click:comments', formElementId: string): void
}>()

const commentStore = useCommentStore()
const { load: loadComments } = commentStore
const { comments } = storeToRefs(commentStore)

const commentActions = useComment(props.applicationFormId)
const {
  submitComment,
  updateEditComment,
  cancelEditComment,
  editComment,
  isEditingComment,
  isCommentByUser,
  commentTextAreaValue
} = commentActions

if (props.applicationFormId) {
  console.log('Loading comments for application form:', props.applicationFormId)
  await loadComments(props.applicationFormId)
}

const activeFormElement = ref('')

// TODO: Lazy loading?
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')
    default:
      return resolveComponent('Unimplemented')
  }
}

function updateFormOptions(formOptions: FormOptionDto[], formElementIndex: number) {
  const updatedModelValue = [...props.modelValue]
  updatedModelValue[formElementIndex] = { ...updatedModelValue[formElementIndex], options: formOptions }
  emit('update:modelValue', updatedModelValue)
}

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

function createChatMessageActions(comment: CommentDto) {
  const chatMessageActions = []

  if (isCommentByUser(comment)) {
    chatMessageActions.push({
      label: 'Edit',
      icon: 'i-lucide-pencil',
      onClick: () => editComment(comment)
    })
  }
  return chatMessageActions
}
</script>
