<template>
  <div class="relative transition-colors transition-300 message-item">
    <a v-if="props.item?.reply_to" :href="`#m${props.item?.reply_to.id}`">
      <div class="pl-2 mb-0.5 text-sm opacity-80 flex items-center">
        <v-icon icon="mdi-reply" class="me-2" />
        <span class="me-1 text-xs overflow-hidden ws-nowarp text-ellipsis">{{ props.item?.reply_to?.content }}</span>
        <span class="text-xs overflow-hidden ws-nowarp text-ellipsis">
          from {{ props.item?.reply_to?.sender.account.name }}
        </span>
      </div>
    </a>

    <div class="flex gap-2">
      <div>
        <v-avatar
          color="grey-lighten-2"
          icon="mdi-account-circle"
          class="rounded-card"
          :image="props.item?.sender.account.avatar"
        />
      </div>

      <div class="flex-grow-1">
        <div class="font-bold text-sm">{{ props.item?.sender.account.nick }}</div>
        <div>{{ props.item?.content }}</div>

        <message-attachment
          v-if="props.item?.attachments && props.item?.attachments.length > 0"
          class="mt-1"
          :attachments="props.item?.attachments"
        />
      </div>

      <div class="transition-opacity transition-300 message-action">
        <v-card>
          <div class="flex px-2 py-0.5">
            <v-btn icon="mdi-reply" size="x-small" variant="text" @click="replyMessage" />
            <v-btn v-if="isOwned" icon="mdi-pencil" size="x-small" variant="text" color="warning" @click="editMessage" />
            <v-btn v-if="isOwned" icon="mdi-delete" size="x-small" variant="text" color="error" @click="deleteMessage" />
          </div>
        </v-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useChannels } from "@/stores/channels"
import { useUserinfo } from "@/stores/userinfo"
import { computed } from "vue"
import MessageAttachment from "@/components/chat/renderer/MessageAttachment.vue"

const id = useUserinfo()
const channels = useChannels()

const props = defineProps<{ item: any }>()

const isOwned = computed(() => props.item?.sender?.id === id.userinfo.idSet.messaging)

function replyMessage() {
  channels.related.messages.reply_to = JSON.parse(JSON.stringify(props.item))
}

function editMessage() {
  channels.related.messages.edit_to = JSON.parse(JSON.stringify(props.item))
}

function deleteMessage() {
  channels.related.messages.delete_to = JSON.parse(JSON.stringify(props.item))
  channels.related.messages.delete_to.channel = channels.current
  channels.show.messages.delete = true
}
</script>

<style scoped>
.rounded-card {
  border-radius: 8px;
}

.message-action {
  position: absolute;
  right: 8px;
  top: -18px;
  opacity: 0;
}

.message-item:hover {
  background-color: rgba(0, 0, 0, .15);
}

.message-item:hover .message-action {
  opacity: 100%;
}
</style>
