<template>
  <template v-if="comments && comments.length > 0">
    <UChatMessages :auto-scroll="false" :should-scroll-to-bottom="false">
      <UChatMessage
        v-for="comment in comments"
        :id="comment.id"
        :key="comment.id"
        :avatar="{ icon: 'i-lucide-bot' }"
        :content="comment.message"
        role="user"
        :parts="[{ type: 'text', text: comment.message }]"
        :side="isCommentByUser(comment) ? 'right' : 'left'"
        variant="subtle"
        :actions="createChatMessageActions(comment)"
      >
        <template>
          <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(formElementId)">
    {{ $t('comments.submit') }}
  </UButton>
  <UButton v-if="isEditingComment" class="my-3 lg:my-4" @click="updateEditComment"> {{ $t('comments.edit') }} </UButton>
  <UButton v-if="isEditingComment" class="my-3 lg:my-4" @click="cancelEditComment"> {{ $t('common.cancel') }} </UButton>
</template>

<script setup lang="ts">
import type { CommentDto } from '~~/.api-client'
import { useCommentTextarea } from '~/composables/comment/useCommentTextarea'

const props = defineProps<{
  formElementId: string
  applicationFormId: string
  comments?: CommentDto[]
}>()

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

function createChatMessageActions(comment: CommentDto) {
  const { t: $t } = useI18n()
  const chatMessageActions = []

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