<template>
    <div class="search-session-page">
        <div class="search-session-content">
            <div class="search-bar">
                <div class="search-box">
                    <svg class="search-icon" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"
                        aria-hidden="true">
                        <path
                            d="M8.75 3.75a5 5 0 1 0 0 10 5 5 0 0 0 0-10Zm0-1.5a6.5 6.5 0 1 1 0 13 6.5 6.5 0 0 1 0-13Zm5.209 11.148 3.02 3.02a.75.75 0 1 1-1.06 1.061l-3.02-3.02a.75.75 0 0 1 1.06-1.06Z"
                            fill="#86909C" />
                    </svg>
                    <input v-model="keyword" class="search-input" type="text" :placeholder="t('搜索名称/userId')"
                        autocomplete="off" />
                </div>
                <button class="cancel-button" type="button" @click="goBack">{{ t('取消') }}</button>
            </div>

            <div class="search-result-list">
                <button v-for="session in filteredSessions" :key="session.itemKey" class="search-result-item"
                    type="button" @click="handleSessionClick(session)">
                    <div class="search-result-main">
                        <div class="search-result-avatar">{{ session.name.slice(0, 1) }}</div>
                        <div class="search-result-name">{{ session.name }}</div>
                    </div>
                    <div v-if="session.tag" class="search-result-tags">
                        <span class="search-result-tag">{{ session.tag }}</span>
                    </div>
                </button>

                <div v-if="filteredSessions.length === 0" class="empty-state">{{ t('暂无结果，试试其他关键词') }}</div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import AIDeskCoreInstance, { SESSION_TYPE, StoreName, type ISessionModel } from '@tencentcloud/ai-desk-core';
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';

interface SearchSessionItem {
    id: string;
    name: string;
    tag: string;
    itemKey: string;
    type: SESSION_TYPE.IM | SESSION_TYPE.ROBOT | SESSION_TYPE.IM_QUEUE | SESSION_TYPE.IM_OTHER_INPROGRESS;
    sessionState?: string;
    isInnerSession?: boolean;
    searchText: string;
}

type SearchSessionSourceItem =
    | ISessionModel<SESSION_TYPE.IM>
    | ISessionModel<SESSION_TYPE.ROBOT>
    | ISessionModel<SESSION_TYPE.IM_QUEUE>
    | ISessionModel<SESSION_TYPE.IM_OTHER_INPROGRESS>;

type SearchCategory = {
    key: string;
    label: string;
    match: (session: SearchSessionSourceItem) => boolean;
};

const router = useRouter();
const { t } = useI18n();
const keyword = ref('');
const IMSessionList = ref<ISessionModel<SESSION_TYPE.IM>[]>([]);
const IMRobotSessionList = ref<ISessionModel<SESSION_TYPE.ROBOT>[]>([]);
const IMQueueSessionList = ref<ISessionModel<SESSION_TYPE.IM_QUEUE>[]>([]);
const IMOtherInprogressSessionList = ref<ISessionModel<SESSION_TYPE.IM_OTHER_INPROGRESS>[]>([]);

onMounted(() => {
    AIDeskCoreInstance.coreStore.watch(StoreName.SESSION, {
        IMSessionList: onIMSessionListUpdated,
        IMRobotSessionList: onIMRobotSessionListUpdated,
        IMQueueSessionList: onIMQueueSessionListUpdated,
        IMOtherInprogressSessionList: onIMOtherInprogressSessionListUpdated,
    });
});

onUnmounted(() => {
    AIDeskCoreInstance.coreStore.unwatch(StoreName.SESSION, {
        IMSessionList: onIMSessionListUpdated,
        IMRobotSessionList: onIMRobotSessionListUpdated,
        IMQueueSessionList: onIMQueueSessionListUpdated,
        IMOtherInprogressSessionList: onIMOtherInprogressSessionListUpdated,
    });
});

const onIMSessionListUpdated = (list: ISessionModel<SESSION_TYPE.IM>[]) => {
    IMSessionList.value = list ?? [];
};

const onIMRobotSessionListUpdated = (list: ISessionModel<SESSION_TYPE.ROBOT>[]) => {
    IMRobotSessionList.value = list ?? [];
};

const onIMQueueSessionListUpdated = (list: ISessionModel<SESSION_TYPE.IM_QUEUE>[]) => {
    IMQueueSessionList.value = list ?? [];
};

const onIMOtherInprogressSessionListUpdated = (list: ISessionModel<SESSION_TYPE.IM_OTHER_INPROGRESS>[]) => {
    IMOtherInprogressSessionList.value = list ?? [];
};

const searchCategories = computed<SearchCategory[]>(() => [
    {
        key: SESSION_TYPE.IM + 'outer',
        label: t('服务中'),
        match: (session) => {
            return session.sessionData.type === SESSION_TYPE.IM &&
                session.sessionData.sessionState === 'inProgress' && !session.sessionData.isInnerSession;
        },
    },
    {
        key: String(SESSION_TYPE.IM_QUEUE),
        label: t('待分配'),
        match: (session) => {
            return session.sessionData.type === SESSION_TYPE.IM_QUEUE;
        },
    },
    {
        key: SESSION_TYPE.IM + 'inner',
        label: t('内部会话'),
        match: (session) => {
            return session.sessionData.type === SESSION_TYPE.IM && session.sessionData.isInnerSession;
        },
    },
    {
        key: SESSION_TYPE.ROBOT + 'robot',
        label: t('智能体服务中'),
        match: (session) => {
            return session.sessionData.type === SESSION_TYPE.ROBOT && session.sessionData.transToAgentTimes === 0;
        },
    },
    {
        key: SESSION_TYPE.ROBOT + 'wait-human',
        label: t('待人工处理'),
        match: (session) => {
            return session.sessionData.type === SESSION_TYPE.ROBOT && session.sessionData.transToAgentTimes > 0;
        },
    },
    {
        key: SESSION_TYPE.IM + 'ended',
        label: t('已结束'),
        match: (session) => {
            return session.sessionData.type === SESSION_TYPE.IM && session.sessionData.sessionState === 'finished';
        },
    },
    {
        key: String(SESSION_TYPE.IM_OTHER_INPROGRESS),
        label: t('全部会话'),
        match: (session) => {
            return session.sessionData.type === SESSION_TYPE.IM_OTHER_INPROGRESS;
        },
    },
]);

const getSessionName = (session: SearchSessionSourceItem) => {
    return session.sessionData.nickname || session.sessionData.userId || session.sessionId;
};

const buildSearchText = (name: string, userId: string | undefined, tags: string[]) => {
    return [name, userId ?? '', ...tags].join(' ').toLowerCase();
};

const getMatchedCategories = (session: SearchSessionSourceItem) => {
    return searchCategories.value.filter((category) => category.match(session));
};

const allSessions = computed<SearchSessionItem[]>(() => {
    return [
        ...IMSessionList.value,
        ...IMRobotSessionList.value,
        ...IMQueueSessionList.value,
        ...IMOtherInprogressSessionList.value,
    ].flatMap((session) => {
        const currentName = getSessionName(session);
        const currentUserId = session.sessionData.userId;
        const matchedCategories = getMatchedCategories(session);

        return matchedCategories.map((category) => {
            return {
                id: session.sessionId,
                name: currentName,
                tag: category.label,
                itemKey: `${session.sessionId}-${category.key}`,
                type: session.sessionData.type,
                sessionState: session.sessionData.type === SESSION_TYPE.IM ? session.sessionData.sessionState : undefined,
                isInnerSession: session.sessionData.type === SESSION_TYPE.IM ? Boolean(session.sessionData.isInnerSession) : undefined,
                searchText: buildSearchText(currentName, currentUserId, [category.label]),
            };
        });
    });
});

const normalizedKeyword = computed(() => keyword.value.trim().toLowerCase());

const filteredSessions = computed(() => {
    if (!normalizedKeyword.value) {
        return allSessions.value;
    }

    return allSessions.value.filter((session) => {
        return session.searchText.includes(normalizedKeyword.value);
    });
});

const handleSessionClick = (session: SearchSessionItem) => {
    if (session.type === SESSION_TYPE.IM) {
        if (session.isInnerSession) {
            AIDeskCoreInstance.chatService.setMessageRead(session.id);
        } else if (session.sessionState === 'ringing' || session.sessionState === 'seatJoining') {
            return;
        } else if (session.sessionState === 'inProgress') {
            AIDeskCoreInstance.chatService.setMessageRead(session.id);
        }
    }

    AIDeskCoreInstance.sessionService.switchSession({ sessionId: session.id, sessionType: session.type })
    router.push({
        path: `/mobileDesk/chat/${session.id}`,
        query: {
            sessionType: session.type,
            sessionName: session.name,
        },
    });
};

const goBack = () => {
    if (window.history.length > 1) {
        router.back();
        return;
    }

    router.push('/mobileDesk/sessionList');
};
</script>

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

.search-session-page {
    height: 100%;
    min-height: 0;
    background: #f5f7fa;
    display: flex;
    flex-direction: column;
}

.search-session-content {
    flex: 1;
    min-height: 0;
    padding: 16px;
    background: #fff;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.search-bar {
    display: flex;
    align-items: center;
    gap: 12px;
}

.search-box {
    flex: 1;
    min-width: 0;
    height: 36px;
    padding: 0 14px;
    display: flex;
    align-items: center;
    gap: 8px;
    border-radius: 22px;
    background: #f2f3f5;
}

.search-icon {
    width: 18px;
    height: 18px;
    flex-shrink: 0;
}

.search-input {
    flex: 1;
    min-width: 0;
    border: none;
    outline: none;
    background: transparent;
    font-size: 14px;
    color: #1d2129;
}

.search-input::placeholder {
    color: #86909c;
}

.cancel-button {
    flex-shrink: 0;
    border: none;
    padding: 0;
    background: transparent;
    color: #1d2129;
    font-size: 14px;
    line-height: 22px;
    cursor: pointer;
}

.search-result-list {
    margin-top: 16px;
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    padding-right: 8px;
    scrollbar-gutter: stable;
}

.search-result-item {
    width: 100%;
    padding: 14px 0;
    border: none;
    background: transparent;
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    cursor: pointer;
}

.search-result-main {
    min-width: 0;
    flex: 1;
    display: flex;
    align-items: center;
    gap: 12px;
}

.search-result-avatar {
    width: 40px;
    height: 40px;
    border-radius: 999px;
    background: #e8f3ff;
    color: #165dff;
    font-size: 18px;
    font-weight: 600;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
}

.search-result-name {
    min-width: 0;
    flex: 1;
    font-size: 15px;
    line-height: 24px;
    color: #1d2129;
    text-align: left;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.search-result-tags {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    gap: 8px;
    flex-wrap: wrap;
}

.search-result-tag {
    flex-shrink: 0;
    padding: 4px 10px;
    border-radius: 999px;
    background: #f2f3f5;
    color: #4e5969;
    font-size: 12px;
    line-height: 20px;
}

.empty-state {
    padding: 24px 0;
    color: #86909c;
    font-size: 12px;
    line-height: 20px;
    text-align: center;
}
</style>