<template>
    <div class="pc-ai-response-button">
        <BaseIconButton :icon="icon" :loading-icon="loadingIcon" :title="t('智能回复')" :disabled="!sessionId"
            :loading="loading" @click="handleTrigger" />

        <div v-if="panelVisible" class="pc-ai-panel" @click.stop>
            <div class="pc-ai-panel-header">
                <span class="pc-ai-panel-title">
                    <svg class="pc-ai-panel-title-icon" viewBox="0 0 16 16" width="16" height="16"
                        xmlns="http://www.w3.org/2000/svg">
                        <path fill="#1a6dff" transform="matrix(1 0 -0.188924 0.981992 2.10546 3.92356)"
                            d="M5.2238 0.9444C5.3439 0.62 5.8027 0.62 5.9227 0.9444C6.6564 2.927 8.2196 4.4902 10.2022 5.2238C10.5266 5.3439 10.5266 5.8027 10.2022 5.9227C8.2196 6.6564 6.6564 8.2196 5.9227 10.2022C5.8027 10.5266 5.3439 10.5266 5.2238 10.2022C4.4902 8.2196 2.927 6.6564 0.9444 5.9227C0.62 5.8027 0.62 5.3439 0.9444 5.2238C2.927 4.4902 4.4902 2.927 5.2238 0.9444Z" />
                        <path fill="#1a6dff" transform="matrix(1 0 -0.188924 0.981992 9.65823 1.13065)"
                            d="M2.7108 0.4901C2.7731 0.3217 3.0112 0.3217 3.0735 0.4901C3.4542 1.5189 4.2654 2.3301 5.2942 2.7108C5.4626 2.7731 5.4626 3.0112 5.2942 3.0735C4.2654 3.4542 3.4542 4.2654 3.0735 5.2942C3.0112 5.4626 2.7731 5.4626 2.7108 5.2942C2.3301 4.2654 1.5189 3.4542 0.4901 3.0735C0.3217 3.0112 0.3217 2.7731 0.4901 2.7108C1.5189 2.3301 2.3301 1.5189 2.7108 0.4901Z" />
                    </svg>
                    <span class="pc-ai-panel-title-text">{{ t('智能回复') }}</span>
                </span>
                <button class="pc-ai-panel-close" type="button" :aria-label="t('关闭')" @click="handleClose">×</button>
            </div>

            <div class="pc-ai-panel-body">
                <p v-if="responseText" class="pc-ai-panel-text">{{ responseText }}</p>
                <p v-else class="pc-ai-panel-placeholder">{{ t('正在生成中...') }}</p>
            </div>

            <div class="pc-ai-panel-footer">
                <button class="pc-ai-panel-regenerate" type="button" :disabled="loading" @click="handleRegenerate">
                    <span class="pc-ai-panel-regenerate-icon" aria-hidden="true">↺</span>
                    <span>{{ t('重新生成') }}</span>
                </button>
                <button class="pc-ai-panel-use" type="button" :disabled="loading || !responseText" @click="handleUse">
                    {{ t('使用') }}
                </button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { v4 as uuidv4 } from 'uuid';
import AIDeskCoreInstance, {
    AI_DESK_EVENTS,
    type AIDeskEventParamsMap,
} from '@tencentcloud/ai-desk-core';
import BaseIconButton from './BaseIconButton.vue';
import aiResponseIcon from '../../../../Mobile/Chat/ChatInput/assets/AIResponse.svg';
import textGeneratingIcon from '../../../../Mobile/Chat/ChatInput/assets/textGenerating.png';

const props = defineProps<{ sessionId: string }>();
const emit = defineEmits<{
    (e: 'use-text', text: string): void;
    (e: 'open'): void;
}>();

const { t } = useI18n();
const icon = aiResponseIcon;
const loadingIcon = textGeneratingIcon;

const loading = ref(false);
const currentReplyId = ref('');
const responseText = ref('');
const panelVisible = ref(false);

const startGenerate = async () => {
    if (!props.sessionId || loading.value) {
        return;
    }

    const replyId = uuidv4();
    currentReplyId.value = replyId;
    responseText.value = '';
    loading.value = true;
    panelVisible.value = true;
    emit('open');

    try {
        await AIDeskCoreInstance.chatService.AIAssistAnswer({
            sessionId: props.sessionId,
            replyId,
        });
    } catch (error) {
        console.error(error);
        currentReplyId.value = '';
        loading.value = false;
    }
};

const handleTrigger = async () => {
    if (panelVisible.value) {
        handleClose();
        return;
    }
    await startGenerate();
};

const handleRegenerate = async () => {
    if (loading.value) {
        return;
    }
    await startGenerate();
};

const handleUse = () => {
    if (!responseText.value || loading.value) {
        return;
    }
    emit('use-text', responseText.value);
    handleClose();
};

const handleClose = () => {
    currentReplyId.value = '';
    loading.value = false;
    responseText.value = '';
    panelVisible.value = false;
};

const onAIAssistAnswerEvent = (data: AIDeskEventParamsMap[AI_DESK_EVENTS.AI_ASSIST_ANSWER_EVENT]) => {
    if (data.sessionId !== props.sessionId) {
        return;
    }
    if (!currentReplyId.value || data.replyId !== currentReplyId.value) {
        return;
    }

    responseText.value = data.chunks.join('').replace(/\n+/g, '');

    if (data.isFinished === 1) {
        loading.value = false;
        currentReplyId.value = '';
    }
};

onMounted(() => {
    AIDeskCoreInstance.eventCenter.addEvent(AI_DESK_EVENTS.AI_ASSIST_ANSWER_EVENT, onAIAssistAnswerEvent);
});

onUnmounted(() => {
    AIDeskCoreInstance.eventCenter.removeEvent(AI_DESK_EVENTS.AI_ASSIST_ANSWER_EVENT, onAIAssistAnswerEvent);
    handleClose();
});

defineExpose({ close: handleClose });
</script>

<style scoped>
.pc-ai-response-button {
    position: relative;
    display: inline-flex;
}

.pc-ai-panel {
    position: absolute;
    left: 50%;
    bottom: calc(100% + 12px);
    z-index: 10;
    width: 380px;
    padding: 14px 16px 12px;
    border-radius: 12px;
    background: #fff;
    box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
    transform: translateX(-50%);
    box-sizing: border-box;
}

.pc-ai-panel::after {
    content: '';
    position: absolute;
    left: 50%;
    bottom: -6px;
    width: 12px;
    height: 12px;
    background: #fff;
    transform: translateX(-50%) rotate(45deg);
    box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.04);
}

.pc-ai-panel-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 8px;
}

.pc-ai-panel-title {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    color: #222;
    font-size: 14px;
    font-weight: 500;
    line-height: 20px;
}

.pc-ai-panel-title-icon {
    display: block;
    width: 16px;
    height: 16px;
}

.pc-ai-panel-title-text {
    line-height: 20px;
}

.pc-ai-panel-close {
    width: 20px;
    height: 20px;
    padding: 0;
    border: none;
    background: transparent;
    color: #676A70;
    font-size: 18px;
    line-height: 18px;
    cursor: pointer;
}

.pc-ai-panel-body {
    max-height: 120px;
    overflow-y: auto;
    padding: 4px 0 8px;
}

.pc-ai-panel-text {
    margin: 0;
    color: #222;
    font-size: 14px;
    line-height: 22px;
    white-space: pre-wrap;
    word-break: break-word;
}

.pc-ai-panel-placeholder {
    margin: 0;
    color: #a5a9b0;
    font-size: 14px;
    line-height: 22px;
}

.pc-ai-panel-footer {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-top: 4px;
}

.pc-ai-panel-regenerate {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 0;
    border: none;
    background: transparent;
    color: #676A70;
    font-size: 13px;
    line-height: 20px;
    cursor: pointer;
}

.pc-ai-panel-regenerate:disabled {
    opacity: 0.5;
    cursor: not-allowed;
}

.pc-ai-panel-regenerate-icon {
    display: inline-block;
    font-size: 14px;
    line-height: 14px;
}

.pc-ai-panel-use {
    height: 32px;
    min-width: 72px;
    padding: 0 20px;
    border: none;
    border-radius: 16px;
    background: #1a6dff;
    color: #fff;
    font-size: 13px;
    line-height: 20px;
    cursor: pointer;
}

.pc-ai-panel-use:disabled {
    background: #b8c9ee;
    cursor: not-allowed;
}
</style>
