<script setup>
import { format, isToday } from 'date-fns'
import dayjs from "dayjs"

definePageMeta({
  middleware: "auth"
})

defineShortcuts({
  ' ': () => {
    document.getElementById("textinput").focus()
  },
})

const itemInfo = ref({})
const dataStore = useDataStore()
const supabase = useSupabaseClient()

const setup = async () => {
  itemInfo.value = await useSupabaseSelectSingle("chats",useRoute().params.id,"*, profiles(*), chatmessages(*)")

  let unseenMessages = itemInfo.value.chatmessages.filter(i => !i.seenBy.includes(dataStore.activeProfile.id))


  for await (const message of unseenMessages){
    await supabase.from("chatmessages").update({seenBy: [...message.seenBy, dataStore.activeProfile.id]}).eq("id",message.id)
  }


}
setup()

const messageText = ref("")
const sendMessage = async () => {
  if(messageText.value.length > 0) {
    const message = {
      origin: dataStore.activeProfile.id,
      destinationchat: itemInfo.value.id,
      text: messageText.value,
      tenant: dataStore.currentTenant,
      seenBy: [dataStore.activeProfile.id]
    }

    const {data,error} = await supabase.from("chatmessages").insert(message)

    if(error) {
      console.log(error)
    } else {
      //Reset
      messageText.value = ""
      //Create Notifications
      let notifications = itemInfo.value.profiles.filter(i => i.id !== dataStore.activeProfile.id).map(i => {
        return {
          tenant: dataStore.currentTenant,
          profile: i.id,
          initiatingProfile: dataStore.activeProfile.id,
          title: `Sie haben eine neue Nachricht im Chat ${itemInfo.value.name}`,
          link: `/chats/show/${itemInfo.value.id}`,
          message: message.text
        }
      })

      console.log(notifications)

      const {error} = await supabase.from("notifications").insert(notifications)

      setup()
    }
  }
}

</script>

<template>
  <UDashboardNavbar :title="itemInfo.name">
    <template #center>

    </template>
    <template #right>
      <UAvatarGroup size="sm" :max="2">
        <UAvatar
            v-if="itemInfo.profiles"
            v-for="avatar in itemInfo.profiles.map(i => i.fullName)"
            :alt="avatar" size="sm" />
      </UAvatarGroup>

    </template>
  </UDashboardNavbar>
  <div class="scrollList p-5">
    <UAlert
        :color="message.seenBy.includes(dataStore.activeProfile.id) ? 'white' : 'primary'"
        :variant="message.seenBy.includes(dataStore.activeProfile.id) ? 'solid' : 'outline'"
        class="my-2"
        v-for="message in itemInfo.chatmessages"
        :description="message.text"
        :avatar="{ alt: dataStore.getProfileById(message.origin).fullName }"
        :title="`${dataStore.getProfileById(message.origin).fullName} - ${isToday(new Date(message.created_at)) ? dayjs(message.created_at).format('HH:mm') : dayjs(message.created_at).format('DD.MM.YYYY HH:mm')}`"
      />

  </div>
  <div class="flex flex-row justify-between p-5">
    <UInput
        class="flex-auto mr-2"
        v-model="messageText"
        @keyup.enter="sendMessage"
        placeholder="Deine Nachricht"
        id="textinput"
    />
    <UButton
        icon="i-heroicons-chevron-double-right-solid"
        @click="sendMessage"
        :disabled="messageText.length === 0"
    >

    </UButton>
  </div>

</template>

<style scoped>

</style>