<template>
  <div class="sm:max-w-prose mx-auto flex gap-3 px-4 pt-0 flex-col-reverse sm:pb-safe-or-4 w-full">
    <!-- Форма отправки сообщений -->
    <form @submit.prevent="sendMessage" class="flex gap-2 items-center" ref="form">
      <InputText
        id="newMessage"
        v-model="newMessage"
        class="flex-1"
        placeholder="Напишите сообщение"
      />
      <Button type="submit" icon="pi pi-send" class="p-button-md" :disabled="!newMessage.trim()" />
    </form>

    <ChatSubscribeWebPush :qr_code_uri :chat :user_chat_role="userRole" />
  </div>
</template>

<script setup lang="ts">
import { ref, useTemplateRef } from 'vue'
const newMessage = ref('')
const formRef = useTemplateRef('form')
import { getBrowserUuid } from '@/utils/getBrowserUuid'
import { getUserUuid } from '@/utils/getUserUuid'
import { type MessageDocument } from '@hereconnect/types'
import { messagesDbLocal as db } from '@/api/dbs'

const { qr_code_uri, chat, userRole } = defineProps<{
  qr_code_uri: MessageDocument['qr_code_uri']
  chat: MessageDocument['chat']
  userRole: MessageDocument['from']
}>()

// onMounted(() => {
//   formRef.value?.querySelector('input')?.focus()
// })

// Отправка нового сообщения
async function sendMessage() {
  const created_at = new Date().toISOString()
  const user_uuid = getUserUuid()
  const message: MessageDocument = {
    _id: `message:${qr_code_uri}:${chat}:${created_at}`,
    type: 'message',
    qr_code_uri,
    chat,
    from: userRole,
    body: newMessage.value.trim(),
    browser_uuid: getBrowserUuid(),
    user_uuid,
    created_at,
  }

  try {
    await db.put(message)
    newMessage.value = ''
    formRef.value?.querySelector('input')?.focus()
  } catch (error) {
    console.error('Ошибка отправки сообщения:', error)
  }
}
</script>
