<template>
    <div class="session-toolbar">
        <div class="profile-section">
            <div class="avatar" aria-hidden="true">
                <img v-if="staffAvatar" class="avatar-image" :src="staffAvatar" alt="" />
                <svg v-else viewBox="0 0 24 24" class="avatar-icon">
                    <path
                        d="M12 12c2.761 0 5-2.239 5-5s-2.239-5-5-5-5 2.239-5 5 2.239 5 5 5Zm0 2c-4.418 0-8 2.91-8 6.5 0 .828.672 1.5 1.5 1.5h13c.828 0 1.5-.672 1.5-1.5C20 16.91 16.418 14 12 14Z" />
                </svg>
            </div>
            <t-popover :visible="visible" placement="top" theme="light" trigger="click" :show-arrow="false"
                @visible-change="handleVisibleChange">
                <template #triggerElement>
                    <div class="status-trigger">
                        <span class="status-dot status-trigger-dot" :style="{ background: currentStatus.color }"></span>
                        <span class="status-trigger-text">{{ currentStatus.label }}</span>
                        <img class="status-trigger-icon" :src="selectDownIcon" alt="" />
                    </div>
                </template>
                <template #content>
                    <div class="custom__list">
                        <template v-for="option in statusOptions" :key="option.key">
                            <t-popover v-if="option.value === 'rest' && option.showArrow"
                                :visible="restReasonPopupVisible" placement="right-top" theme="light" trigger="manual"
                                :show-arrow="false">
                                <template #triggerElement>
                                    <div class="status-option-wrapper">
                                        <button type="button" class="status-option"
                                            :class="{ 'status-option--active': option.selected }"
                                            @click="handleStatusSelect(option)">
                                            <span class="status-dot" :style="{ background: option.color }"></span>
                                            <span class="status-option-text">{{ option.label }}</span>
                                            <span class="status-option-arrow">&gt;</span>
                                        </button>
                                    </div>
                                </template>
                                <template #content>
                                    <div class="custom__list rest-reason-list">
                                        <button v-for="reasonItem in enabledRestReasonList" :key="reasonItem.name"
                                            type="button" class="status-option rest-reason-option"
                                            :class="{ 'status-option--active': isRestReasonSelected(reasonItem.name) }"
                                            @click="handleRestReasonSelect(reasonItem.name)">
                                            <span class="status-option-text">{{ reasonItem.name }}</span>
                                        </button>
                                    </div>
                                </template>
                            </t-popover>
                            <button v-else type="button" class="status-option"
                                :class="{ 'status-option--active': option.selected }"
                                @click="handleStatusSelect(option)">
                                <span class="status-dot" :style="{ background: option.color }"></span>
                                <span class="status-option-text">{{ option.label }}</span>
                            </button>
                        </template>
                    </div>
                </template>
            </t-popover>
        </div>

        <div class="action-buttons">
            <div class="icon-button" @click="goToSearchSession">
                <img class="button-icon" :src="sessionListSearchIcon" alt="" />
            </div>
            <div class="icon-button" @click="goToCreateSession">
                <svg viewBox="0 0 24 24" class="button-icon add-icon" aria-hidden="true">
                    <path d="M12 5v14M5 12h14" />
                </svg>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import sessionListSearchIcon from '../../../../../assets/icons/sessionListSearch.svg';
import selectDownIcon from './selectDown.svg';
import AIDeskCoreInstance, { StoreName } from '@tencentcloud/ai-desk-core';

type StatusOption = {
    key: string;
    value: 'free' | 'notReady' | 'rest' | 'offline';
    label: string;
    color: string;
    selected: boolean;
    showArrow?: boolean;
};

type RestReasonItem = {
    name: string;
    state: string;
};

type ConnectionState = 'disconnected' | 'connected' | 'connecting' | 'reconnecting';
type UserStatus = 'offline' | 'free' | 'busy' | 'rest' | 'countdown' | 'arrange' | 'notReady';
type LogicStatus = 'ready' | 'notReady' | 'rest' | 'afterCallWork' | 'offline' | '';

const router = useRouter();
const { t } = useI18n();
const visible = ref(false);
const status = ref<UserStatus>('offline');
const logicStatus = ref<LogicStatus>('');
const reason = ref<string>('');
const staffAvatar = ref<string>('');
const staffName = ref<string>('');
const connectionState = ref<ConnectionState>('disconnected');
const restReasonPopupVisible = ref(false);
const restReasonList = ref<RestReasonItem[]>([]);

onMounted(() => {
    AIDeskCoreInstance.coreStore.watch(StoreName.USERINFO, {
        status: onStatusUpdated,
        logicStatus: onLogicStatusUpdated,
        reason: onReasonUpdated,
        staffAvatar: onStaffAvatarUpdated,
        staffName: onStaffNameUpdated,
        connectionState: onConnectionStateUpdated,
    });
    AIDeskCoreInstance.coreStore.watch(StoreName.APP_SETTING, {
        restReasonList: onRestReasonListUpdated,
    });
});

onUnmounted(() => {
    AIDeskCoreInstance.coreStore.unwatch(StoreName.USERINFO, {
        status: onStatusUpdated,
        logicStatus: onLogicStatusUpdated,
        reason: onReasonUpdated,
        staffAvatar: onStaffAvatarUpdated,
        staffName: onStaffNameUpdated,
        connectionState: onConnectionStateUpdated,
    });
    AIDeskCoreInstance.coreStore.unwatch(StoreName.APP_SETTING, {
        restReasonList: onRestReasonListUpdated,
    });
});

const onStatusUpdated = (newStatus: UserStatus) => {
    status.value = newStatus;
};

const onLogicStatusUpdated = (newLogicStatus: LogicStatus) => {
    logicStatus.value = newLogicStatus ?? '';
};

const onReasonUpdated = (newReason: string) => {
    reason.value = newReason ?? '';
};

const onStaffAvatarUpdated = (newStaffAvatar: string) => {
    staffAvatar.value = newStaffAvatar ?? '';
};

const onStaffNameUpdated = (newStaffName: string) => {
    staffName.value = newStaffName ?? '';
};

const onConnectionStateUpdated = (newConnectionState: ConnectionState) => {
    connectionState.value = newConnectionState;
};

const handleVisibleChange = (val: boolean) => {
    visible.value = val;
    if (!val) {
        restReasonPopupVisible.value = false;
    }
};



const onRestReasonListUpdated = (newRestReasonList: RestReasonItem[]) => {
    restReasonList.value = newRestReasonList ?? [];
};

const enabledRestReasonList = computed(() => {
    return restReasonList.value.filter((item) => item.state === '1');
});

const isFreeSelected = computed(() => {
    return status.value === 'free' && logicStatus.value === 'ready';
});

const isNotReadySelected = computed(() => {
    return status.value === 'busy'
        ? logicStatus.value === 'notReady'
        : status.value === 'notReady';
});

const isRestSelected = computed(() => {
    return status.value === 'busy'
        ? logicStatus.value === 'rest'
        : status.value === 'rest';
});

const statusOptions = computed<StatusOption[]>(() => {
    if (connectionState.value === 'connected') {
        return [
            {
                key: 'free',
                value: 'free',
                label: t('示闲'),
                color: '#00B42A',
                selected: isFreeSelected.value,
            },
            {
                key: 'notReady',
                value: 'notReady',
                label: t('示忙'),
                color: '#E54545',
                selected: isNotReadySelected.value,
            },
            {
                key: 'rest',
                value: 'rest',
                label: t('小休'),
                color: '#FF7D00',
                selected: isRestSelected.value,
                showArrow: enabledRestReasonList.value.length > 0,
            },
            {
                key: 'offline',
                value: 'offline',
                label: t('下线'),
                color: '#A5A9B0',
                selected: status.value === 'offline',
            },
        ];
    }

    if (connectionState.value === 'disconnected') {
        return [
            {
                key: 'online',
                value: 'free',
                label: t('上线'),
                color: '#00B42A',
                selected: false,
            },
            {
                key: 'offline',
                value: 'offline',
                label: t('下线'),
                color: '#A5A9B0',
                selected: status.value === 'offline',
            },
        ];
    }

    return [];
});

const currentStatus = computed(() => {
    if (connectionState.value === 'disconnected') {
        return {
            label: t('下线'),
            color: '#A5A9B0',
        };
    }

    if (isRestSelected.value) {
        return {
            label: t('小休'),
            color: '#FF7D00',
        };
    }

    if (isNotReadySelected.value) {
        return {
            label: t('示忙'),
            color: '#E54545',
        };
    }

    if (isFreeSelected.value) {
        return {
            label: t('示闲'),
            color: '#00B42A',
        };
    }

    return {
        label: t('下线'),
        color: '#A5A9B0',
    };
});

const handleSetStatus = (nextStatus: 'offline' | 'free' | 'rest' | 'notReady', restReason?: string) => {
    AIDeskCoreInstance.userInfoService.setStatus({
        status: nextStatus,
        restReason,
    });
};

const handleStatusSelect = (selectedStatus: StatusOption) => {
    if (selectedStatus.value === 'rest' && enabledRestReasonList.value.length > 0) {
        restReasonPopupVisible.value = !restReasonPopupVisible.value;
        return;
    }

    if (selectedStatus.key === 'online') {
        AIDeskCoreInstance.userInfoService.online();
        restReasonPopupVisible.value = false;
        visible.value = false;
        return;
    }

    if (selectedStatus.value === 'offline') {
        AIDeskCoreInstance.userInfoService.offline();
        restReasonPopupVisible.value = false;
        visible.value = false;
        return;
    }

    handleSetStatus(selectedStatus.value);
    restReasonPopupVisible.value = false;
    visible.value = false;
};

const handleRestReasonSelect = (restReason: string) => {
    handleSetStatus('rest', restReason);
    restReasonPopupVisible.value = false;
    visible.value = false;
};

const isRestReasonSelected = (restReasonName: string) => {
    return isRestSelected.value && reason.value === restReasonName;
};

const goToSearchSession = () => {
    router.push('/mobileDesk/sessionList/search');
};

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

<style scoped>
.session-toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    padding: 12px 16px 0;
    background: #fff;
}

.profile-section {
    flex: 1;
    min-width: 0;
    display: flex;
    align-items: center;
    gap: 10px;
}

.avatar {
    width: 38px;
    height: 38px;
    flex-shrink: 0;
    border-radius: 50%;
    background: #f2f3f5;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
}

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

.avatar-icon {
    width: 20px;
    height: 20px;
    fill: #1d2129;
}

.status-trigger {
    min-width: 88px;
    max-width: 100%;
    height: 36px;
    padding: 0;
    border-radius: 18px;
    background: transparent;
    display: flex;
    align-items: center;
    gap: 6px;
    color: #1d2129;
    font-size: 18px;
    cursor: pointer;
    -webkit-tap-highlight-color: transparent;
    user-select: none;
    -webkit-user-select: none;
    -webkit-touch-callout: none;
}

.status-trigger-dot {
    width: 8px;
    height: 8px;
    flex-shrink: 0;
}

.status-trigger-text {
    line-height: 1;
    max-width: 120px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.status-trigger-icon {
    width: 16px;
    height: 16px;
    display: block;
    flex-shrink: 0;
}

.custom__list {
    width: max-content;
    padding: 0;
    border-radius: 12px;
    background: #fff;
}

.custom__list> :deep(.t-popup__reference) {
    display: block;
    width: 100%;
}

.status-option-wrapper {
    display: block;
    width: 100%;
}

.status-option {
    width: 100%;
    height: 36px;
    padding: 0 12px;
    display: flex;
    align-items: center;
    gap: 8px;
    background: #fff;
    color: #000;
    font-size: 14px;
    white-space: nowrap;
    cursor: pointer;
    -webkit-tap-highlight-color: transparent;
    border: none;
    border-radius: 6px;
    margin-bottom: 2px;
}

.status-option:last-child {
    margin-bottom: 0;
}

.status-option:hover,
.status-option:active {
    background: #fff;
}

.status-option--active {
    background: #f0f2f7ff !important;
}

.status-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    flex-shrink: 0;
}

.status-option-text {
    flex: 0 0 auto;
    color: #000;
    line-height: 20px;
    text-align: left;
}

.status-option-arrow {
    margin-left: auto;
    color: #86909c;
    font-size: 14px;
    line-height: 1;
}

.action-buttons {
    display: flex;
    align-items: center;
    gap: 8px;
}

.icon-button {
    width: 36px;
    height: 36px;
    padding: 0;
    border: 1px solid #e5e6eb;
    border-radius: 18px;
    background: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    -webkit-tap-highlight-color: transparent;
    user-select: none;
    -webkit-user-select: none;
    -webkit-touch-callout: none;
}

.button-icon {
    width: 14px;
    height: 14px;
    display: block;
}

.add-icon {
    fill: none;
    stroke: #1d2129;
    stroke-width: 2;
    stroke-linecap: round;
}

.rest-reason-list {
    max-height: 240px;
    overflow-y: auto;
}

.rest-reason-option {
    width: 100%;
    padding: 0 14px;
}
</style>