<template>
    <div class="detail-page">
        <header class="detail-header">
            <button class="header-action" type="button" @click="goBack">
                <img class="header-action-icon" :src="pageBackIcon" alt="" />
            </button>
            <div class="detail-title">{{ t('转接会话') }}</div>
            <div class="header-placeholder" />
        </header>

        <div class="detail-content">
            <div class="transfer-switch">
                <button class="transfer-switch-button" :class="{ 'is-active': activeTransferTab === 'member' }"
                    type="button" @click="setActiveTransferTab('member')">
                    {{ t('成员') }}
                </button>
                <button class="transfer-switch-button" :class="{ 'is-active': activeTransferTab === 'group' }"
                    type="button" @click="setActiveTransferTab('group')">
                    {{ t('分组') }}
                </button>
            </div>

            <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="searchKeyword" class="search-input" type="text" :placeholder="searchPlaceholder"
                        autocomplete="off" />
                </div>
            </div>

            <div class="transfer-list">
                <template v-if="activeTransferTab === 'member'">
                    <button v-for="contact in contacts" :key="contact.userId" class="contact-item" type="button"
                        @click="openTransferConfirmForMember(contact)">
                        <div class="contact-avatar">
                            <img v-if="contact.avatar" class="contact-avatar-image" :src="contact.avatar" alt="" />
                            <span v-else>{{ contact.name.slice(0, 1) }}</span>
                        </div>
                        <div class="contact-name-line">
                            <span class="contact-text">
                                <span class="contact-name" v-html="highlightKeyword(contact.name)"></span>
                                <span class="contact-id">（<span
                                        v-html="highlightKeyword(contact.userId)"></span>）</span>
                            </span>
                        </div>
                    </button>
                </template>

                <template v-else>
                    <button v-for="group in skillGroups" :key="group.skillGroupId" class="group-item" type="button"
                        @click="openTransferConfirmForGroup(group)">
                        <div class="group-main">
                            <div class="group-name" v-html="highlightKeyword(group.skillGroupName)"></div>
                            <div class="group-meta">{{ t('技能组ID：{id}', { id: group.skillGroupId }) }}</div>
                        </div>
                        <div class="group-count">{{ t('{count}人空闲', { count: group.freeStaffCount }) }}</div>
                    </button>
                </template>

                <div v-if="currentLoading && currentListLength === 0" class="empty-state">
                    {{ t('加载中...') }}
                </div>
                <div v-else-if="currentLoadError && currentListLength === 0" class="empty-state">
                    {{ currentLoadError }}
                </div>
                <div v-else-if="!currentLoading && currentListLength === 0" class="empty-state">
                    {{ activeTransferTab === 'member' ? t('未找到匹配的客服信息') : t('未找到匹配的分组信息') }}
                </div>
            </div>
        </div>

        <t-dialog class="confirm-dialog" v-model:visible="confirmDialogVisible" :close-on-overlay-click="true"
            :confirm-btn="null" :cancel-btn="null" @confirm="handleTransferConfirm" @cancel="handleTransferCancel">
            <template #middle>
                <div class="transfer-dialog-content">
                    <div class="transfer-dialog-text">{{ transferConfirmText }}</div>
                    <div class="transfer-dialog-actions">
                        <button type="button" class="transfer-dialog-button transfer-dialog-button--cancel"
                            @click="handleTransferCancel">
                            {{ t('取消转接') }}
                        </button>
                        <button type="button" class="transfer-dialog-button transfer-dialog-button--confirm"
                            @click="handleTransferConfirm">
                            {{ t('确定转接') }}
                        </button>
                    </div>
                </div>
            </template>
        </t-dialog>
    </div>
</template>

<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import debounce from 'lodash/debounce';
import AIDeskCoreInstance, { StoreName } from '@tencentcloud/ai-desk-core';
import pageBackIcon from '../../../../assets/icons/pageBack.svg';
import toast from '../../../../utils/toast';

interface ContactItem {
    userId: string;
    name: string;
    avatar: string;
}

interface SkillGroupItem {
    skillGroupId: string;
    skillGroupName: string;
    freeStaffCount: number;
}

type TransferTarget =
    | {
        type: 'member';
        contact: ContactItem;
    }
    | {
        type: 'group';
        group: SkillGroupItem;
    }
    | null;

type TransferTab = 'member' | 'group';

const skillGroupTypeMap = {
    IM: 1 as const,
};

const route = useRoute();
const router = useRouter();
const { t } = useI18n();
const activeTransferTab = ref<TransferTab>('member');
const searchKeyword = ref('');
const contacts = ref<ContactItem[]>([]);
const skillGroups = ref<SkillGroupItem[]>([]);
const memberLoading = ref(false);
const groupLoading = ref(false);
const memberLoadError = ref('');
const groupLoadError = ref('');
const confirmDialogVisible = ref(false);
const pendingTransferTarget = ref<TransferTarget>(null);
const currentUserId = ref('');

const sessionId = computed(() => route.params.sessionId as string);
const normalizedKeyword = computed(() => searchKeyword.value.trim());
const searchPlaceholder = computed(() => {
    return activeTransferTab.value === 'member' ? t('搜索姓名、邮箱') : t('搜索组名、成员');
});
const currentLoading = computed(() => {
    return activeTransferTab.value === 'member' ? memberLoading.value : groupLoading.value;
});
const currentLoadError = computed(() => {
    return activeTransferTab.value === 'member' ? memberLoadError.value : groupLoadError.value;
});
const currentListLength = computed(() => {
    return activeTransferTab.value === 'member' ? contacts.value.length : skillGroups.value.length;
});
const transferConfirmText = computed(() => {
    if (!pendingTransferTarget.value) {
        return '';
    }

    if (pendingTransferTarget.value.type === 'member') {
        const { name, userId } = pendingTransferTarget.value.contact;
        return t('确定将会话转接至{name}（{userId}）', { name, userId });
    }

    return t('确定将会话转接至技能组 {name}', { name: pendingTransferTarget.value.group.skillGroupName });
});

const loadContacts = async () => {
    memberLoading.value = true;
    memberLoadError.value = '';

    try {
        const result = await AIDeskCoreInstance.sessionService.getStaffList({
            pageNum: 0,
            pageSize: 2000,
            status: [100, 700],
            isNeedStatus: true,
            skillGroupType: skillGroupTypeMap.IM,
            ...(normalizedKeyword.value && { fuzzingKeyWord: normalizedKeyword.value }),
        });

        contacts.value = result.staffList
            .filter((staff) => staff.userId !== currentUserId.value)
            .map((staff) => {
                return {
                    userId: staff.userId,
                    name: staff.nickName || staff.staffName || staff.userId,
                    avatar: staff.avatar || '',
                };
            });
    } catch (error) {
        console.error(error);
        contacts.value = [];
        memberLoadError.value = t('获取客服列表失败');
    } finally {
        memberLoading.value = false;
    }
};

const loadSkillGroups = async () => {
    groupLoading.value = true;
    groupLoadError.value = '';

    try {
        const result = await AIDeskCoreInstance.sessionService.getSkillGroupList({
            skillGroupType: skillGroupTypeMap.IM,
            ...(normalizedKeyword.value && { fuzzingKeyWord: normalizedKeyword.value }),
        });

        skillGroups.value = (result.skillGroupList ?? []).map((item) => {
            return {
                skillGroupId: item.skillGroupId,
                skillGroupName: item.skillGroupName,
                freeStaffCount: item.freeCntExceptReqMember ?? item.freeStaffCount ?? 0,
            };
        });
    } catch (error) {
        console.error(error);
        skillGroups.value = [];
        groupLoadError.value = t('获取分组列表失败');
    } finally {
        groupLoading.value = false;
    }
};

const fetchTransferList = debounce(() => {
    if (activeTransferTab.value === 'member') {
        loadContacts();
        return;
    }

    loadSkillGroups();
}, 300);

onMounted(() => {
    AIDeskCoreInstance.coreStore.watch(StoreName.USERINFO, {
        userId: onCurrentUserIdUpdated,
    });
    fetchTransferList();
});

onBeforeUnmount(() => {
    AIDeskCoreInstance.coreStore.unwatch(StoreName.USERINFO, {
        userId: onCurrentUserIdUpdated,
    });
    fetchTransferList.cancel();
});

const onCurrentUserIdUpdated = (userId: string) => {
    currentUserId.value = userId ?? '';
};

watch([searchKeyword, activeTransferTab], () => {
    fetchTransferList();
});

const escapeHtml = (value: string) => {
    return value
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/\"/g, '&quot;')
        .replace(/'/g, '&#39;');
};

const escapeRegExp = (value: string) => {
    return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
};

const highlightKeyword = (value: string) => {
    const safeValue = escapeHtml(value);

    if (!normalizedKeyword.value) {
        return safeValue;
    }

    const pattern = new RegExp(`(${escapeRegExp(normalizedKeyword.value)})`, 'ig');
    return safeValue.replace(pattern, '<span class="keyword-highlight">$1</span>');
};

const setActiveTransferTab = (tab: TransferTab) => {
    activeTransferTab.value = tab;
};

const openTransferConfirmForMember = (contact: ContactItem) => {
    pendingTransferTarget.value = {
        type: 'member',
        contact,
    };
    confirmDialogVisible.value = true;
};

const openTransferConfirmForGroup = (group: SkillGroupItem) => {
    pendingTransferTarget.value = {
        type: 'group',
        group,
    };
    confirmDialogVisible.value = true;
};

const handleTransferCancel = () => {
    confirmDialogVisible.value = false;
    pendingTransferTarget.value = null;
};

const handleTransferConfirm = async () => {
    const target = pendingTransferTarget.value;

    if (!target) {
        confirmDialogVisible.value = false;
        return;
    }

    confirmDialogVisible.value = false;

    if (target.type === 'member') {
        await transferToMember(target.contact);
    } else {
        await transferToGroup(target.group);
    }

    pendingTransferTarget.value = null;
};

const transferToMember = async (contact: ContactItem) => {
    try {
        await AIDeskCoreInstance.sessionService.transferSession({
            sessionId: sessionId.value,
            userId: contact.userId,
        });
        AIDeskCoreInstance.sessionService.switchSession({ sessionId: '', sessionType: '' })
        router.replace({
            path: '/mobileDesk/sessionList',
        });
    } catch (error) {
        console.error(error);
        toast.error(t('转接失败'));
    }
};

const transferToGroup = async (group: SkillGroupItem) => {
    try {
        await AIDeskCoreInstance.sessionService.transferSession({
            sessionId: sessionId.value,
            skillGroupId: group.skillGroupId,
        });
        AIDeskCoreInstance.sessionService.switchSession({ sessionId: '', sessionType: '' })
        router.replace({
            path: '/mobileDesk/sessionList',
        });
    } catch (error) {
        console.error(error);
        toast.error(t('转接失败'));
    }
};

const goBack = () => {
    router.back();
};
</script>

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

.detail-page {
    height: 100%;
    display: flex;
    flex-direction: column;
    background: #f5f7fa;
}

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

.header-action,
.header-placeholder {
    width: 32px;
    height: 32px;
    flex-shrink: 0;
}

.header-action {
    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;
}

.detail-title {
    flex: 1;
    text-align: center;
    font-size: 16px;
    font-weight: 600;
    color: #222;
}

.detail-content {
    flex: 1;
    min-height: 0;
    padding: 16px;
    display: flex;
    flex-direction: column;
    gap: 12px;
    overflow: hidden;
}

.transfer-switch {
    display: flex;
    gap: 0;
    padding: 4px;
    background: #f2f3f5;
    border-radius: 20px;
}

.transfer-switch-button {
    flex: 1;
    height: 36px;
    border: none;
    border-radius: 16px;
    background: transparent;
    color: #86909c;
    font-size: 14px;
    font-weight: 500;
    cursor: pointer;
}

.transfer-switch-button.is-active {
    background: #fff;
    color: #1d2129;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

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

.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;
}

.transfer-list {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
}

.contact-item {
    width: 100%;
    padding: 8px 0;
    border: none;
    background: transparent;
    text-align: left;
    cursor: pointer;
    display: flex;
    align-items: center;
    gap: 12px;
}

.contact-avatar {
    width: 40px;
    height: 40px;
    border-radius: 999px;
    background: transparent;
    color: #165dff;
    font-size: 20px;
    font-weight: 600;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    overflow: hidden;
}

.contact-avatar-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.contact-name-line {
    min-width: 0;
    flex: 1;
}

.contact-text {
    display: block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.contact-name {
    font-size: 15px;
    line-height: 24px;
    color: #1d2129;
}

.contact-id {
    margin-left: 4px;
    font-size: 13px;
    line-height: 20px;
    color: #86909c;
}

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

.group-main {
    min-width: 0;
    flex: 1;
}

.group-name {
    font-size: 15px;
    line-height: 24px;
    color: #1d2129;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.group-meta {
    margin-top: 2px;
    font-size: 13px;
    line-height: 20px;
    color: #86909c;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

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

:deep(.keyword-highlight) {
    color: #165dff;
}

.empty-state {
    padding: 28px 0;
    text-align: center;
    font-size: 14px;
    color: #86909c;
}

.transfer-dialog-content {
    padding: 16px 16px 0;
}

.transfer-dialog-text {
    color: #1d2129;
    font-size: 16px;
    line-height: 26px;
    text-align: left;
    white-space: normal;
    word-break: break-all;
    overflow-wrap: anywhere;
}

.transfer-dialog-actions {
    margin-top: 20px;
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 20px;
}

.transfer-dialog-button {
    flex: 1;
    height: 40px;
    border: none;
    border-radius: 999px;
    font-size: 15px;
    line-height: 22px;
    cursor: pointer;
}

.transfer-dialog-button--cancel {
    background: #F0F2F7;
    color: #000;
}

.transfer-dialog-button--confirm {
    background: #000;
    color: #fff;
}
</style>