<template>
    <div class="create-session-page">
        <header class="create-session-header">
            <button class="close-button" type="button" @click="goBack">
                <svg width="14" height="14" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M12 4L4 12M4 4L12 12" stroke="#222" stroke-width="1.5" stroke-linecap="round"
                        stroke-linejoin="round" />
                </svg>
            </button>
            <div class="header-title">{{ t('发起会话') }}</div>
            <div class="header-placeholder" />
        </header>

        <div class="create-session-content">
            <div class="contact-switch">
                <button class="contact-switch-button" :class="{ 'is-active': activeContactType === 'internal' }"
                    type="button" @click="setActiveContactType('internal')">
                    {{ t('内部联系人') }}
                </button>
                <button class="contact-switch-button" :class="{ 'is-active': activeContactType === 'external' }"
                    type="button" @click="setActiveContactType('external')">
                    {{ t('外部联系人') }}
                </button>
            </div>

            <div v-if="activeContactType === 'internal'" class="internal-contact-card">
                <div class="field-label">{{ t('联系人名称/邮箱') }}</div>
                <button class="contact-picker" type="button" @click="goToInternalContactPicker">
                    <span class="contact-picker-text" :class="{ 'is-selected': Boolean(selectedContactText) }">
                        {{ selectedContactText || t('请选择') }}
                    </span>
                    <span class="contact-picker-arrow">&gt;</span>
                </button>
            </div>

            <div v-else class="external-contact-card">
                <div class="identity-card">
                    <div class="field-label">{{ t('我的身份') }}</div>
                    <button class="contact-picker" type="button" @click="openIdentityPicker">
                        <span class="contact-picker-text" :class="{ 'is-selected': Boolean(selectedMyIdentityText) }">
                            {{ selectedMyIdentityText || t('请选择') }}
                        </span>
                        <span class="contact-picker-arrow">&gt;</span>
                    </button>
                </div>
                <div class="field-label">{{ t('联系人 IM UserID') }}</div>
                <button class="contact-picker" type="button" @click="goToExternalContactPicker">
                    <span class="contact-picker-text" :class="{ 'is-selected': Boolean(selectedExternalContactText) }">
                        {{ selectedExternalContactText || t('搜索 IM UserID') }}
                    </span>
                    <span class="contact-picker-arrow">&gt;</span>
                </button>
            </div>
        </div>

        <div class="create-session-footer">
            <button type="button" class="submit-button" :class="{ 'submit-button--disabled': !canCreateSession }"
                :disabled="!canCreateSession" @click="handleCreateSession">
                {{ t('发起会话') }}
            </button>
        </div>

        <t-popup v-model="identityState.show" placement="bottom">
            <t-picker v-model="identityState.value" :title="t('选择您的身份')" :columns="identityOptions"
                @confirm="handleIdentityConfirm" @cancel="handleIdentityCancel" />
        </t-popup>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue';
import type { PickerValue } from 'tdesign-mobile-vue';
import { useRoute, useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import AIDeskCoreInstance, { SESSION_TYPE, StoreName } from '@tencentcloud/ai-desk-core';
import toast from '../../../../utils/toast';
import { parseUnknownError } from '../../../../utils/parseUnknownError';

type ContactType = 'internal' | 'external';

type IdentityOptionItem = {
    label: string;
    value: string;
};

const router = useRouter();
const route = useRoute();
const { t } = useI18n();
const identityOptions = ref<IdentityOptionItem[]>([]);
const imContactUserEnable = ref(false);

onMounted(() => {
    loadIdentityOptions();
    AIDeskCoreInstance.coreStore.watch(StoreName.APP_SETTING, {
        imContactUserEnable: onIMContactUserEnableUpdated,
    });
});

onUnmounted(() => {
    AIDeskCoreInstance.coreStore.unwatch(StoreName.APP_SETTING, {
        imContactUserEnable: onIMContactUserEnableUpdated,
    });
});

const onIMContactUserEnableUpdated = (value: boolean) => {
    imContactUserEnable.value = value;
};

const selectedName = computed(() => {
    const value = route.query.name ?? route.query.contactName;
    return typeof value === 'string' ? value : '';
});

const selectedUserId = computed(() => {
    const value = route.query.userId ?? route.query.contactEmail;
    return typeof value === 'string' ? value : '';
});

const selectedExternalImUserId = computed(() => {
    const value = route.query.externalImUserId;
    return typeof value === 'string' ? value : '';
});

const selectedExternalContactName = computed(() => {
    const value = route.query.externalContactName;
    return typeof value === 'string' ? value : '';
});

const selectedMyIdentity = computed(() => {
    const value = route.query.myIdentity;
    return typeof value === 'string' ? value : '';
});

const defaultMyIdentity = computed(() => {
    return identityOptions.value[0]?.value || '';
});

const selectedMyIdentityText = computed(() => {
    const currentIdentity = identityOptions.value.find((item) => item.value === selectedMyIdentity.value);
    return currentIdentity?.label || '';
});

const identityState = reactive({
    show: false,
    value: [selectedMyIdentity.value || defaultMyIdentity.value],
});

const activeContactType = computed<ContactType>(() => {
    if (route.query.contactType === 'external') {
        return 'external';
    }

    if (route.query.contactType === 'internal') {
        return 'internal';
    }

    if (selectedExternalImUserId.value) {
        return 'external';
    }

    return 'internal';
});

const selectedContactText = computed(() => {
    return selectedName.value || selectedUserId.value || '';
});

const selectedExternalContactText = computed(() => {
    if (selectedExternalContactName.value && selectedExternalImUserId.value) {
        return `${selectedExternalContactName.value}（${selectedExternalImUserId.value}）`;
    }

    return selectedExternalContactName.value || selectedExternalImUserId.value || '';
});

const canCreateSession = computed(() => {
    if (activeContactType.value === 'internal') {
        return Boolean(selectedUserId.value);
    }

    return Boolean(selectedExternalImUserId.value) && Boolean(selectedMyIdentity.value);
});

const loadIdentityOptions = async () => {
    try {
        const result = await AIDeskCoreInstance.sessionService.getIMAgentList();
        identityOptions.value = result.map((item) => {
            return {
                label: item.nickName || item.userId,
                value: item.userId,
            };
        });

        if (!selectedMyIdentity.value && defaultMyIdentity.value) {
            identityState.value = [defaultMyIdentity.value];
        }
    } catch (error) {
        console.error(error);
        identityOptions.value = [];
    }
};

const setActiveContactType = (contactType: ContactType) => {
    if (contactType === 'external' && !imContactUserEnable.value) {
        toast.warn(t('当前未开启外部联系人会话'));
        return;
    }

    router.replace({
        path: '/mobileDesk/sessionList/create',
        query: {
            ...route.query,
            contactType,
        },
    });
};

const goToInternalContactPicker = () => {
    router.push({
        path: '/mobileDesk/sessionList/internalContacts',
        query: {
            contactType: 'internal',
            name: selectedName.value || undefined,
            userId: selectedUserId.value || undefined,
            externalContactName: selectedExternalContactName.value || undefined,
            externalImUserId: selectedExternalImUserId.value || undefined,
            myIdentity: selectedMyIdentity.value || undefined,
        },
    });
};

const goToExternalContactPicker = () => {
    router.push({
        path: '/mobileDesk/sessionList/externalContacts',
        query: {
            contactType: 'external',
            name: selectedName.value || undefined,
            userId: selectedUserId.value || undefined,
            externalContactName: selectedExternalContactName.value || undefined,
            externalImUserId: selectedExternalImUserId.value || undefined,
            myIdentity: selectedMyIdentity.value || undefined,
        },
    });
};

const openIdentityPicker = () => {
    identityState.value = [selectedMyIdentity.value || defaultMyIdentity.value];
    identityState.show = true;
};

const handleIdentityCancel = () => {
    identityState.show = false;
    identityState.value = [selectedMyIdentity.value || defaultMyIdentity.value];
};

const handleIdentityConfirm = (value: PickerValue[]) => {
    const identity = value.length > 0 ? String(value[0]) : '';

    router.replace({
        path: '/mobileDesk/sessionList/create',
        query: {
            ...route.query,
            contactType: 'external',
            myIdentity: identity || undefined,
        },
    });

    identityState.show = false;
};

const handleCreateSession = () => {
    if (activeContactType.value === 'internal') {
        if (!selectedUserId.value) {
            toast.warn(t('请选择联系人'));
            return;
        }

        try {
            const sessionId = `C2C${selectedUserId.value}`;
            const sessionName = selectedName.value || selectedUserId.value;

            AIDeskCoreInstance.sessionService.startInnerSession(
                selectedUserId.value,
                sessionName,
            );
            AIDeskCoreInstance.sessionService.switchSession({ sessionId: sessionId, sessionType: SESSION_TYPE.IM })
            router.push({
                path: `/mobileDesk/chat/${sessionId}`,
                query: {
                    sessionType: SESSION_TYPE.IM,
                    sessionName,
                },
            });
        } catch (error) {
            console.error(error);
            toast.error(t('发起内部会话失败'));
        }
        return;
    }

    if (!selectedExternalImUserId.value) {
        toast.warn(t('请选择联系人'));
        return;
    }

    if (!selectedMyIdentity.value) {
        toast.warn(t('请选择身份'));
        return;
    }

    try {
        AIDeskCoreInstance.sessionService.followUpSession(
            selectedExternalImUserId.value,
            selectedMyIdentity.value,
        );
        router.push('/mobileDesk/sessionList');
    } catch (error) {
        console.error(error);
        toast.error(parseUnknownError(error))
    }
};

const goBack = () => {
    router.push('/mobileDesk/sessionList');
};
</script>

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

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

.create-session-header {
    height: 60px;
    padding: 0 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #fff;
}

.close-button,
.header-placeholder {
    width: 56px;
    flex-shrink: 0;
}

.close-button {
    width: 32px;
    height: 32px;
    border: 1px solid #dcdee0;
    background: #fff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    padding: 0;
}

.header-title {
    flex: 1;
    text-align: center;
    font-size: 16px;
}

.create-session-content {
    flex: 1;
    min-height: 0;
    padding: 16px;
    background: #fff;
}

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

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

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

.internal-contact-card,
.external-contact-card {
    margin-top: 16px;
}

.identity-card {
    margin-bottom: 16px;
}

.field-label {
    font-size: 14px;
    font-weight: 500;
    line-height: 22px;
    color: #1d2129;
}

.contact-picker {
    width: 100%;
    margin-top: 12px;
    padding: 0 16px;
    height: 48px;
    border: 1px solid #dcdfe5;
    border-radius: 24px;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    cursor: pointer;
}

.contact-picker-text {
    flex: 1;
    min-width: 0;
    text-align: left;
    font-size: 14px;
    color: #86909c;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.contact-picker-text.is-selected {
    color: #1d2129;
}

.contact-picker-arrow {
    margin-left: 12px;
    color: #86909c;
    font-size: 16px;
    line-height: 1;
}

.create-session-footer {
    padding: 12px 0 24px;
    display: flex;
    justify-content: center;
    background: #fff;
    flex-shrink: 0;
}

.submit-button {
    width: 80%;
    height: 44px;
    border: none;
    border-radius: 22px;
    background: #000;
    color: #fff;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
}

.submit-button--disabled {
    background: rgba(0, 0, 0, 0.05999999865889549);
    cursor: not-allowed;
}
</style>