<template>
    <div v-if="hasQuoteMessage && quoteMessage" class="message-quote-container" @click="handleClick">
        <div class="quote-message-line"></div>
        <div class="quote-message-content">
            <div class="quote-message-sender">
                {{ displaySender }}
            </div>
            <div class="quote-message-abstract">
                {{ displayAbstract }}
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'

import { parseUnknownError } from '../../../../utils/parseUnknownError'
import toast from '../../../../utils/toast'
import type { IMessageModel } from '@tencentcloud/ai-desk-core'

interface QuoteMessageData {
    messageAbstract?: string
    messageType?: number
    messageSenderNick?: string
    messageSender?: string
    messageID?: string
}

interface CloudCustomData {
    messageReply?: QuoteMessageData
}

interface Props {
    message: IMessageModel
    status: string
    messageListDom: HTMLDivElement | null
}

const props = defineProps<Props>()
const { t } = useI18n()

const parseCloudCustomData = (message: IMessageModel): CloudCustomData | null => {
    try {
        if (!message?.cloudCustomData) {
            return null
        }

        const parsed = JSON.parse(message.cloudCustomData)
        return parsed && typeof parsed === 'object' ? (parsed as CloudCustomData) : null
    } catch {
        return null
    }
}

const getDefaultMessageAbstract = (messageType?: number) => {
    switch (messageType) {
        case 3:
            return t('[图片消息]')
        case 4:
            return t('[语音消息]')
        case 5:
            return t('[视频消息]')
        case 6:
            return t('[文件消息]')
        case 2:
            return t('[自定义消息]')
        default:
            return ''
    }
}

const showQuoteMissingError = () => {
    toast.error(t('引用消息不存在'))
}

const escapeSelectorId = (value: string) => {
    if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') {
        return CSS.escape(value)
    }

    return value.replace(/([^a-zA-Z0-9_-])/g, '\\$1')
}

const quoteMessage = computed(() => parseCloudCustomData(props.message)?.messageReply ?? null)
const hasQuoteMessage = computed(() => Boolean(quoteMessage.value))

const displaySender = computed(() => {
    return quoteMessage.value?.messageSenderNick?.trim() || quoteMessage.value?.messageSender || ''
})

const displayAbstract = computed(() => {
    const messageAbstract = quoteMessage.value?.messageAbstract?.trim()
    return messageAbstract || getDefaultMessageAbstract(quoteMessage.value?.messageType)
})

const jumpQuoteMessage = () => {
    try {
        if (!props.messageListDom) {
            return
        }

        const messageID = quoteMessage.value?.messageID
        if (!messageID) {
            showQuoteMissingError()
            return
        }

        const escapedMessageID = escapeSelectorId(messageID)
        const element = props.messageListDom.querySelector(`#${escapedMessageID}`) as HTMLElement | null

        if (!element) {
            showQuoteMissingError()
            return
        }

        element.scrollIntoView({
            block: 'center',
            inline: 'nearest',
        })

        const elementContent = props.messageListDom.querySelector(
            `#${escapedMessageID}content`,
        ) as HTMLElement | null

        elementContent?.animate(
            [
                { opacity: 1 },
                {
                    opacity: 1,
                    backgroundColor: '#ff9c19',
                    boxShadow: '0px 0px 10px 0px rgba(255, 156, 25, 1)',
                },
                { opacity: 1 },
            ],
            2000,
        )
    } catch (error) {
        toast.error(parseUnknownError(error))
    }
}

const handleClick = () => {
    if (props.status === '400') {
        return
    }

    jumpQuoteMessage()
}
</script>

<style scoped>
.message-quote-container {
    max-width: 272px;
    margin-top: 4px;
    padding-bottom: 10px;
    font-size: 12px;
    color: #666;
    word-wrap: break-word;
    word-break: break-all;
    background-color: transparent;
    border-radius: 8px;
    line-height: 16.8px;
    cursor: pointer;
    -webkit-tap-highlight-color: transparent;
    width: min(272px, 100%);
    display: flex;
}

.quote-message-line {
    height: 100%;
    width: 2px;
    background: rgba(153, 162, 178, 1);
    margin-right: 6px;
    flex-shrink: 0;
}

.quote-message-content {
    min-width: 0;
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.quote-message-sender {
    font-weight: 500;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

.quote-message-abstract {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}
</style>