<template>
  <PrimeScrollPanel class="flex-1 min-h-0">
    <div v-auto-animate class="flex flex-col gap-3">
      <div
        v-for="message in messages"
        :key="message.id"
        class="min-w-64 w-fit max-w-[60%]"
        :class="{
          'ml-auto': message.sender === me?.username,
        }"
      >
        <p
          v-if="message.sender !== me?.username"
          class="text-sm text-muted-color mb-1"
        >
          {{ message.sender }}
        </p>

        <div
          class="px-2 py-1 rounded-lg"
          :class="{
            'bg-surface-800': message.sender !== me?.username,
            'bg-surface-700': message.sender === me?.username,
          }"
        >
          <p v-html="parseMessageText(message.text)" />
          <p class="text-right text-sm text-muted-color">
            {{ formatDate(message.createdAt) }}
          </p>
        </div>
      </div>
    </div>
  </PrimeScrollPanel>

  <div class="pt-3 mt-auto">
    <PrimeInputGroup>
      <!--      <PrimeInputGroupAddon> -->
      <!--        <PrimeButton severity="secondary" class="shrink-0" disabled> -->
      <!--          <template #icon> -->
      <!--            <Paperclip /> -->
      <!--          </template> -->
      <!--        </PrimeButton> -->
      <!--      </PrimeInputGroupAddon> -->

      <PrimeInputText v-model="text" placeholder="Write a message..." fluid @keydown.enter="sendMessage" />

      <PrimeButton class="shrink-0" label="Send" severity="contrast" @click="sendMessage" />
    </PrimeInputGroup>
  </div>
</template>

<script setup lang="ts">
import { format } from 'date-fns'
import linkifyStr from 'linkify-string'
import { useChat } from '~/composables/use-chat'

definePageMeta({
  name: 'Index',
})

const { me } = useClients()
const chat = useChat()
const { messages } = chat

const text = ref('')

function parseMessageText(text: string) {
  return linkifyStr(text, { className: 'underline', rel: 'noopener noreferrer', target: '_blank' })
}

function formatDate(date: string) {
  return format(date, 'HH:mm')
}

function sendMessage() {
  if (!text.value)
    return

  chat.sendMessage({
    text: text.value,
  })

  text.value = ''
}
</script>
