<template>
    <header class="pc-chat-header">
        <div class="pc-chat-header-left">
            <div class="pc-chat-header-title">{{ sessionShowName }}</div>
            <div v-if="sessionSubTitle" class="pc-chat-header-subtitle">{{ sessionSubTitle }}</div>
        </div>
        <div v-if="headerActions.length" class="pc-chat-header-actions">
            <button v-for="action in headerActions" :key="action.key" class="pc-header-action-button"
                :class="action.className" :ref="(el) => setActionButtonRef(el, action.key)" type="button"
                @click="handleHeaderAction(action.key)">
                <img v-if="action.icon" class="pc-header-action-icon" :src="action.icon" alt="" />
                <svg v-else-if="action.svg === 'user'" class="pc-header-action-icon" viewBox="0 0 20 20" fill="none"
                    xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                    <path
                        d="M10 2.5a3.75 3.75 0 1 1 0 7.5 3.75 3.75 0 0 1 0-7.5Zm0 1.5a2.25 2.25 0 1 0 0 4.5 2.25 2.25 0 0 0 0-4.5Zm-6.25 13.5a6.25 6.25 0 1 1 12.5 0 .75.75 0 0 1-1.5 0 4.75 4.75 0 1 0-9.5 0 .75.75 0 0 1-1.5 0Z"
                        fill="currentColor" />
                </svg>
                <span>{{ action.label }}</span>
            </button>
        </div>

        <ChatTransfer v-if="session && session.type === SESSION_TYPE.IM" v-model:visible="transferPopoverVisible"
            :session-id="session.sessionId" :anchor="transferAnchor" @transferred="handleTransferred" />

        <ChatBlacklist
            v-if="imBlackUserEnable && session && session.type === SESSION_TYPE.IM"
            v-model:mode="blacklistDialogMode" :session="session" @success="handleBlacklistSuccess" />
    </header>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import AIDeskCoreInstance, {
    SESSION_TYPE,
    StoreName,
    type ISessionModel,
    type SessionTypeMap,
} from '@tencentcloud/ai-desk-core';
import correctIcon from '../../../../assets/icons/correct.svg';
import blackListIcon from './blackList.svg';
import transferIcon from './transfer.svg';
import endSessionIcon from './endSession.svg';
import ChatTransfer from '../ChatTransfer/index.vue';
import ChatBlacklist from '../ChatBlacklist/index.vue';
import { getSessionShowSource } from '../../../../utils/index.ts';

type IMSession = ISessionModel<SESSION_TYPE.IM>;
type BlacklistInfo = NonNullable<IMSession['sessionData']['userBlacklist']>;

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

const props = defineProps<{
    session: SessionTypeMap[SESSION_TYPE] | null;
}>();

const emit = defineEmits<{
    (event: 'transfer'): void;
    (event: 'end'): void;
    (event: 'complete'): void;
}>();

const { t } = useI18n();

const transferPopoverVisible = ref(false);
const transferAnchor = ref<HTMLElement | null>(null);
const actionButtonRefs = new Map<string, HTMLElement>();
const blacklistDialogMode = ref<'add' | 'remove' | null>(null);
const imBlackUserEnable = ref(false);

// 单独跟踪 IMSessionList 中当前会话最新的黑名单信息，避免 currentSession watcher 未随黑名单变化触发导致 UI 无法更新
const latestBlacklistInfo = ref<BlacklistInfo | null>(null);

const onIMSessionListUpdated = (list: IMSession[] | undefined) => {
    if (!Array.isArray(list) || !props.session || props.session.type !== SESSION_TYPE.IM) {
        latestBlacklistInfo.value = null;
        return;
    }
    const matched = list.find((item) => item.sessionData?.sessionId === props.session?.sessionId);
    latestBlacklistInfo.value = matched?.sessionData?.userBlacklist ?? null;
};

onMounted(() => {
    AIDeskCoreInstance.coreStore.watch(StoreName.SESSION, {
        IMSessionList: onIMSessionListUpdated,
    });
    AIDeskCoreInstance.coreStore.watch(StoreName.APP_SETTING, {
        imBlackUserEnable: onImBlackUserEnableUpdated,
    });
});

onUnmounted(() => {
    AIDeskCoreInstance.coreStore.unwatch(StoreName.SESSION, {
        IMSessionList: onIMSessionListUpdated,
    });
    AIDeskCoreInstance.coreStore.unwatch(StoreName.APP_SETTING, {
        imBlackUserEnable: onImBlackUserEnableUpdated,
    });
});

const onImBlackUserEnableUpdated = (value: boolean) => {
    imBlackUserEnable.value = value ?? false;
    if (!imBlackUserEnable.value) {
        blacklistDialogMode.value = null;
    }
};

const setActionButtonRef = (el: unknown, key: string) => {
    if (el instanceof HTMLElement) {
        actionButtonRefs.set(key, el);
        if (key === 'transfer') {
            transferAnchor.value = el;
        }
    } else {
        actionButtonRefs.delete(key);
    }
};

const sessionShowName = computed(() => {
    if (!props.session) {
        return '';
    }

    return props.session.nickname || props.session.userId || '';
});

const sessionSubTitle = computed(() => {
    if (!props.session || props.session.type !== SESSION_TYPE.IM) {
        return '';
    }

    if (props.session.isInnerSession) {
        return '';
    }

    const source = getSessionShowSource(
        props.session.peerSource || '',
        props.session.clientData,
    ) || '';
    const channelName = props.session.channelName || '';
    if (!source && !channelName) {
        return '';
    }
    return channelName ? `${source}@${channelName}` : source;
});

const isBlacklisted = computed(() => {
    if (!props.session || props.session.type !== SESSION_TYPE.IM) {
        return false;
    }
    const userBlacklist = latestBlacklistInfo.value ?? props.session.userBlacklist;
    if (!userBlacklist) {
        return false;
    }
    const currentTimestamp = Math.floor(Date.now() / 1000);
    return currentTimestamp <= userBlacklist.endTime;
});

const headerActions = computed<HeaderActionItem[]>(() => {
    if (!props.session || props.session.type !== SESSION_TYPE.IM || props.session.isInnerSession) {
        return [];
    }

    const blacklistAction: HeaderActionItem = {
        key: 'blacklist',
        label: isBlacklisted.value ? t('移出黑名单') : t('加入黑名单'),
        className: 'normal-button',
        icon: blackListIcon,
    };

    switch (props.session.sessionState) {
        case 'inProgress':
            return [
                ...(imBlackUserEnable.value ? [blacklistAction] : []),
                {
                    key: 'transfer',
                    label: t('转接'),
                    className: 'normal-button',
                    icon: transferIcon,
                },
                {
                    key: 'end',
                    label: t('结束'),
                    className: 'end-button',
                    icon: endSessionIcon,
                },
            ];
        case 'finished':
            return [
                ...(imBlackUserEnable.value ? [blacklistAction] : []),
                {
                    key: 'complete',
                    label: t('完成服务'),
                    className: 'normal-button',
                    icon: correctIcon,
                },
            ];
        default:
            return imBlackUserEnable.value ? [blacklistAction] : [];
    }
});

const handleHeaderAction = (key: HeaderActionItem['key']) => {
    if (!props.session) {
        return;
    }

    const sessionId = props.session.sessionId;

    switch (key) {
        case 'transfer':
            transferAnchor.value = actionButtonRefs.get('transfer') ?? null;
            transferPopoverVisible.value = !transferPopoverVisible.value;
            emit('transfer');
            break;
        case 'end':
            AIDeskCoreInstance.sessionService.endSession(sessionId);
            emit('end');
            break;
        case 'complete':
            AIDeskCoreInstance.sessionService.completeSession(sessionId);
            emit('complete');
            break;
        case 'blacklist':
            if (!imBlackUserEnable.value) {
                break;
            }
            blacklistDialogMode.value = isBlacklisted.value ? 'remove' : 'add';
            break;
        default:
            break;
    }
};

const handleTransferred = () => {
    transferPopoverVisible.value = false;
    AIDeskCoreInstance.sessionService.switchSession({ sessionId: '', sessionType: '' });
};

const handleBlacklistSuccess = () => {
    blacklistDialogMode.value = null;
};
</script>

<style scoped>
.pc-chat-header {
    height: 52px;
    padding: 0 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    border-bottom: 1px solid #f0f0f0;
    background: #fff;
    flex-shrink: 0;
}

.pc-chat-header-left {
    min-width: 0;
    flex: 1;
    display: flex;
    align-items: baseline;
    gap: 8px;
    overflow: hidden;
}

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

.pc-chat-header-subtitle {
    color: #a5a9b0;
    font-size: 12px;
    line-height: 20px;
    flex-shrink: 0;
}

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

.pc-header-action-button {
    height: 32px;
    padding: 0 12px;
    border-radius: 6px;
    border: none;
    background: transparent;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
    font-size: 14px;
    line-height: 20px;
    color: #222;
    cursor: pointer;
}

.pc-header-action-button:hover {
    background: #f5f7fa;
}

.pc-header-action-button.end-button {
    color: #E54545;
}

.pc-header-action-icon {
    width: 16px;
    height: 16px;
    display: block;
}
</style>
