<template>
    <div class="internal-contacts-page">
        <div class="internal-contacts-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="contact-list">
                <button v-for="contact in contacts" :key="contact.userId" class="contact-item" type="button"
                    @click="selectContact(contact)">
                    <div class="contact-avatar">
                        <img v-if="contact.avatar" class="contact-avatar-image" :src="contact.avatar" alt="" />
                        <span v-else class="contact-avatar-placeholder" aria-hidden="true">
                            <svg viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <circle cx="20" cy="20" r="20" fill="#E8F3FF" />
                                <circle cx="20" cy="16" r="6" fill="#165DFF" fill-opacity="0.18" />
                                <path d="M10 31C10 26.5817 13.5817 23 18 23H22C26.4183 23 30 26.5817 30 31V32H10V31Z"
                                    fill="#165DFF" fill-opacity="0.18" />
                            </svg>
                        </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>

                <div v-if="!normalizedKeyword" class="empty-state">
                    {{ t('请输入 UserID 后搜索') }}
                </div>
                <div v-else-if="loading && contacts.length === 0" class="empty-state">
                    {{ t('加载中...') }}
                </div>
                <div v-else-if="loadError && contacts.length === 0" class="empty-state">
                    {{ loadError }}
                </div>
                <div v-else-if="!loading && contacts.length === 0" class="empty-state">
                    {{ t('未找到匹配的联系人') }}
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { computed, onBeforeUnmount, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import debounce from 'lodash/debounce';
import AIDeskCoreInstance from '@tencentcloud/ai-desk-core';

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

const router = useRouter();
const route = useRoute();
const { t } = useI18n();
const keyword = ref('');
const contacts = ref<ContactItem[]>([]);
const loading = ref(false);
const loadError = ref('');

const normalizedKeyword = computed(() => keyword.value.trim());
const searchedUserIds = computed(() => {
    return normalizedKeyword.value
        .split(',')
        .map((item) => item.trim())
        .filter(Boolean);
});

const fetchContacts = async () => {
    if (searchedUserIds.value.length === 0) {
        contacts.value = [];
        loadError.value = '';
        loading.value = false;
        return;
    }

    loading.value = true;
    loadError.value = '';

    try {
        const result = await AIDeskCoreInstance.sessionService.getIMUserProfile(searchedUserIds.value);

        contacts.value = result.map((item) => {
            return {
                userId: item.userId,
                name: item.nickName || item.userId,
                avatar: '',
            };
        });
    } catch (error) {
        console.error(error);
        contacts.value = [];
        loadError.value = t('获取联系人失败');
    } finally {
        loading.value = false;
    }
};

const debouncedFetchContacts = debounce(() => {
    fetchContacts();
}, 300);

onBeforeUnmount(() => {
    debouncedFetchContacts.cancel();
});

watch(keyword, () => {
    debouncedFetchContacts();
});

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 selectContact = (contact: ContactItem) => {
    router.push({
        path: '/mobileDesk/sessionList/create',
        query: {
            contactType: 'external',
            name: typeof route.query.name === 'string'
                ? route.query.name
                : typeof route.query.contactName === 'string'
                    ? route.query.contactName
                    : undefined,
            userId: typeof route.query.userId === 'string'
                ? route.query.userId
                : typeof route.query.contactEmail === 'string'
                    ? route.query.contactEmail
                    : undefined,
            externalContactName: contact.name,
            externalImUserId: contact.userId,
            myIdentity: typeof route.query.myIdentity === 'string' ? route.query.myIdentity : undefined,
        },
    });
};

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

    router.push({
        path: '/mobileDesk/sessionList/create',
        query: {
            contactType: 'external',
            name: typeof route.query.name === 'string'
                ? route.query.name
                : typeof route.query.contactName === 'string'
                    ? route.query.contactName
                    : undefined,
            userId: typeof route.query.userId === 'string'
                ? route.query.userId
                : typeof route.query.contactEmail === 'string'
                    ? route.query.contactEmail
                    : undefined,
            externalContactName: typeof route.query.externalContactName === 'string'
                ? route.query.externalContactName
                : undefined,
            externalImUserId: typeof route.query.externalImUserId === 'string'
                ? route.query.externalImUserId
                : undefined,
            myIdentity: typeof route.query.myIdentity === 'string' ? route.query.myIdentity : undefined,
        },
    });
};
</script>
<style scoped>
:deep(*) {
    box-sizing: border-box;
}

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

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

.contact-list {
    margin-top: 20px;
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    gap: 12px;
    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-avatar-placeholder {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.contact-avatar-placeholder svg {
    width: 100%;
    height: 100%;
    display: block;
}

.contact-name-line {
    display: flex;
    align-items: center;
    gap: 4px;
    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;
}

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

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