<template>
  <div class="sm:max-w-prose mx-auto flex gap-3 px-4 pb-3 flex-col-reverse w-full">
    <!-- Форма отправки сообщений -->
    <form @submit.prevent="sendMessage" class="flex gap-2 items-center" ref="form">
      <InputText
        id="newMessage"
        v-model="newMessage"
        class="flex-1 dark:bg-gray-800 dark:text-gray-300 dark:border-gray-700"
        placeholder="Напишите сообщение"
      />
      <Button
        type="submit"
        icon="pi pi-send"
        class="p-button-md dark:bg-primary-600 dark:hover:bg-primary-700"
        :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>
