<template>
    <div class="chat-page">
        <div class="chat-main" v-show="!showChildPage">
            <header class="chat-header">
                <div class="header-left">
                    <button class="header-action" type="button" @click="goBack">
                        <img class="header-action-icon" :src="pageBackIcon" alt="" />
                    </button>
                    <div class="header-title">{{ sessionShowName }}</div>
                </div>

                <div v-if="headerActions.length" class="header-actions">
                    <button v-for="action in headerActions" :key="action.key" class="session-action-button"
                        :class="action.className" type="button" @click="handleHeaderAction(action.key)">
                        <img v-if="action.icon" class="button-icon" :src="action.icon" alt="" />
                        <span>{{ action.label }}</span>
                    </button>
                </div>
            </header>

            <div class="message-list-panel">
                <MessageList :re-edit-message="handleReEditMessage" :footer-action-disabled="isFooterActionDisabled"
                    :on-avatar-click="handleAvatarClick" />
            </div>

            <ChatInput v-if="showChatInput" ref="chatInputRef" :session-id="currentSessionId"
                :is-inner-session="isCurrentInnerSession" />
        </div>

        <router-view />
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import MessageList from '../../../components/MessageList/index.vue';
import ChatInput from './ChatInput/index.vue';
import AIDeskCoreInstance, { SESSION_TYPE, StoreName, type IMessageModel, type SessionTypeMap } from '@tencentcloud/ai-desk-core';
import toast from '../../../utils/toast';
import pageBackIcon from '../../../assets/icons/pageBack.svg';
import correctIcon from '../../../assets/icons/correct.svg';

const route = useRoute();
const router = useRouter();
const { t } = useI18n();
const sessionShowName = ref('');
const currentSessionId = ref('');
const currentSession = ref<SessionTypeMap[SESSION_TYPE] | null>(null);
const isCurrentInnerSession = computed(
    () => currentSession.value?.type === SESSION_TYPE.IM
        && Boolean(currentSession.value.isInnerSession),
);
const isFooterActionDisabled = ref(false);
const chatInputRef = ref<{ setText: (text?: string) => Promise<void> } | null>(null);
const lastIMSessionState = ref('');

interface HeaderActionItem {
    key: string;
    label: string;
    className: string;
    icon?: string;
}

type ConnectionState = 'disconnected' | 'connected' | 'connecting' | 'reconnecting';

const onConnectionStateUpdated = (state: ConnectionState) => {
    if (state === 'disconnected') {
        void router.replace('/mobileDesk/sessionList');
    }
};

const onIMNetStatusUpdated = (state: ConnectionState) => {
    if (state === 'disconnected' || state === 'reconnecting') {
        void router.replace('/mobileDesk/sessionList');
    }
};

const isFromRecord = computed(() => route.query.fromRecord === 'true');

const showChatInput = computed(() => {
    if (!currentSession.value) {
        return false;
    }

    return currentSession.value.type === SESSION_TYPE.IM
        && currentSession.value.sessionState === 'inProgress';
});

const shouldDisableFooterAction = (session: SessionTypeMap[SESSION_TYPE]) => {
    if (session.type === SESSION_TYPE.ROBOT) {
        return ['my', 'other', 'allocation'].includes(session.transferStatus);
    }

    if (session.type === SESSION_TYPE.IM_QUEUE) {
        return session.currentState !== 'Queueing';
    }

    if (session.type === SESSION_TYPE.IM_OTHER_INPROGRESS) {
        return session.memberOutType === 1 || session.memberOutType === 2;
    }

    return false;
};

const syncFooterActionDisabled = (session: SessionTypeMap[SESSION_TYPE] | null) => {
    isFooterActionDisabled.value = session ? shouldDisableFooterAction(session) : false;
};

const showChildPage = computed(() => route.path !== `/mobileDesk/chat/${currentSessionId.value}`);

onMounted(() => {
    AIDeskCoreInstance.coreStore.watch(StoreName.SESSION, {
        currentSession: onCurrentSessionUpdated,
    });
    AIDeskCoreInstance.coreStore.watch(StoreName.USERINFO, {
        connectionState: onConnectionStateUpdated,
        IMNetStatus: onIMNetStatusUpdated,
    });
});

onUnmounted(() => {
    AIDeskCoreInstance.coreStore.unwatch(StoreName.SESSION, {
        currentSession: onCurrentSessionUpdated,
    });
    AIDeskCoreInstance.coreStore.unwatch(StoreName.USERINFO, {
        connectionState: onConnectionStateUpdated,
        IMNetStatus: onIMNetStatusUpdated,
    });
});

const onCurrentSessionUpdated = (session: {
    sessionId: string;
    sessionType: SESSION_TYPE | '';
    sessionData: SessionTypeMap[SESSION_TYPE] | null
}) => {
    const sessionInfo = session.sessionData;
    const previousIMSessionState = lastIMSessionState.value;

    if (sessionInfo === null) {
        currentSession.value = null;
        currentSessionId.value = session.sessionId;
        sessionShowName.value = '';
        lastIMSessionState.value = '';
        syncFooterActionDisabled(null);
        return;
    }

    currentSession.value = sessionInfo;
    sessionShowName.value = sessionInfo.nickname || sessionInfo.userId;
    currentSessionId.value = sessionInfo.sessionId;

    const nextIMSessionState = sessionInfo.type === SESSION_TYPE.IM
        ? sessionInfo.sessionState
        : '';

    lastIMSessionState.value = nextIMSessionState;
    syncFooterActionDisabled(sessionInfo);

    if (previousIMSessionState === 'inProgress' && nextIMSessionState === 'finished') {
        toast.warn(t('当前会话已结束'));
        AIDeskCoreInstance.sessionService.switchSession({ sessionId: '', sessionType: '' });
        router.replace('/mobileDesk/sessionList');
    }
};

const goBack = () => {
    router.back();
    AIDeskCoreInstance.sessionService.switchSession({ sessionId: '', sessionType: '' })
};

const goTransfer = () => {
    router.push({
        path: `/mobileDesk/chat/${currentSessionId.value}/transfer`,
    });
};

const handleEndSession = () => {
    AIDeskCoreInstance.sessionService.endSession(currentSessionId.value);
    goBack();
};

const handleCompleteSession = () => {
    AIDeskCoreInstance.sessionService.completeSession(currentSessionId.value);
    goBack();
};

const handleReEditMessage = (message: IMessageModel) => {
    chatInputRef.value?.setText(typeof message.payload?.text === 'string' ? message.payload.text : '');
};

const handleAvatarClick = () => {
    if (currentSession.value?.type !== SESSION_TYPE.IM || currentSession.value.sessionState !== 'inProgress' || currentSession.value.isInnerSession || currentSession?.value.imAgentChatType === 1) {
        return;
    }

    router.push({
        path: `/mobileDesk/chat/${currentSessionId.value}/profile`,
    });
};

const handleHeaderAction = (actionKey: HeaderActionItem['key']) => {
    switch (actionKey) {
        case 'transfer':
            goTransfer();
            break;
        case 'end':
            handleEndSession();
            break;
        case 'complete':
            handleCompleteSession();
            break;
        default:
            break;
    }
};

const headerActions = computed<HeaderActionItem[]>(() => {
    if (currentSession.value?.type !== SESSION_TYPE.IM || currentSession.value.isInnerSession) {
        return [];
    }
    const sessionState = currentSession.value.sessionState;

    switch (sessionState) {
        case 'inProgress':
            return [
                {
                    key: 'transfer',
                    label: t('转接'),
                    className: 'normal-button',
                },
                {
                    key: 'end',
                    label: t('结束'),
                    className: 'end-button',
                },
            ];
        case 'finished':
            if (isFromRecord.value) {
                return [];
            }
            return [
                {
                    key: 'complete',
                    label: t('完成服务'),
                    className: 'normal-button',
                    icon: correctIcon,
                },
            ];
        default:
            return [];
    }
});
</script>

<style scoped>
:deep(*) {
    box-sizing: border-box;
}

.chat-page {
    height: 100%;
    background: #f5f7fa;
}

.chat-main {
    height: 100%;
    display: flex;
    flex-direction: column;
}

.chat-header {
    height: 52px;
    padding: 0 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    background: #f5f7fa;
}

.header-left {
    min-width: 0;
    flex: 1;
    display: flex;
    align-items: center;
    gap: 12px;
}

.header-action {
    width: 32px;
    height: 32px;
    flex-shrink: 0;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border: none;
    border-radius: 16px;
    background: #fff;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
    padding: 0;
}

.header-action-icon {
    width: 18px;
    height: 18px;
    display: block;
}

.header-title {
    min-width: 0;
    flex: 1;
    font-size: 16px;
    font-weight: 600;
    color: #222;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.header-actions {
    display: flex;
    align-items: center;
    gap: 14px;
    flex-shrink: 0;
}

.session-action-button {
    min-width: 52px;
    height: 32px;
    padding: 0 12px;
    border-radius: 16px;
    border: 1px solid transparent;
    background: #fff;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    font-size: 14px;
    line-height: 20px;
    white-space: nowrap;
}

.session-action-button:disabled {
    opacity: 1;
}

.end-button {
    color: #E54545;
    border: 1px solid #E54545;
}

.normal-button {
    min-width: auto;
    color: #222;
    border: 1px solid #d9d9d9;
}

.button-icon {
    width: 14px;
    height: 14px;
    display: block;
}

.message-list-panel {
    flex: 1;
    min-height: 0;
}
</style>