<template>
    <div class="tabs-wrapper">
        <div class="tabs tabs-pc">
            <span v-for="tab in visibleTabOptions" :key="tab.key" class="tab-item"
                :class="{ active: isSameTab(modelValue, tab.value) }" @click="handleTabChange(tab.value)">
                <span class="tab-icon"
                    :style="{ '-webkit-mask-image': `url(&quot;${tab.icon}&quot;)`, 'mask-image': `url(&quot;${tab.icon}&quot;)` }"></span>
                <span class="tab-label">{{ tab.label }}</span>
                <span v-if="getSessionCount(tab.key) > 0" class="tab-count">
                    {{ getSessionCount(tab.key) }}
                </span>
            </span>

            <template v-if="showRobotGroup">
                <div class="tab-group-header" @click="toggleRobotGroup">
                    <span class="tab-group-arrow" :class="{ collapsed: !robotGroupExpanded }">▾</span>
                    <span class="tab-group-title">{{ t('智能体') }}</span>
                </div>
                <template v-if="robotGroupExpanded">
                    <span v-for="tab in robotGroupTabs" :key="tab.key" class="tab-item tab-item-sub"
                        :class="{ active: isSameTab(modelValue, tab.value) }" @click="handleTabChange(tab.value)">
                        <span class="tab-icon"
                            :style="{ '-webkit-mask-image': `url(&quot;${tab.icon}&quot;)`, 'mask-image': `url(&quot;${tab.icon}&quot;)` }"></span>
                        <span class="tab-label">{{ tab.label }}</span>
                        <span v-if="getSessionCount(tab.key) > 0" class="tab-count">
                            {{ getSessionCount(tab.key) }}
                        </span>
                    </span>
                </template>
            </template>

            <span class="tab-item" :class="{ active: isSameTab(modelValue, serviceRecordTabValue) }"
                @click="handleTabChange(serviceRecordTabValue)">
                <span class="tab-label">{{ t('服务记录') }}</span>
            </span>

            <div v-for="group in visibleMoreGroupOptions" :key="`group-${group.key}`" class="tab-item"
                :class="{ active: isSameTab(modelValue, group.value) }" @click="handleTabChange(group.value)">
                <span class="tab-label">{{ group.label }}</span>
                <span v-if="getSessionCount(group.key) > 0" class="tab-count">
                    {{ getSessionCount(group.key) }}
                </span>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from "vue";
import { useI18n } from 'vue-i18n';
import AIDeskCoreInstance, {
    SESSION_TYPE,
    StoreName,
    type ISessionModel,
} from "@tencentcloud/ai-desk-core";
import servingIcon from "../../../Mobile/SessionsList/components/SessionTabs/serving.svg";
import ringingIcon from "../../../Mobile/SessionsList/components/SessionTabs/ringing.svg";
import robotServingIcon from "../../../Mobile/SessionsList/components/SessionTabs/robotServing.svg";
import waitHumanIcon from "../../../Mobile/SessionsList/components/SessionTabs/waitHuman.svg";

type SessionTabType =
    | SESSION_TYPE.IM
    | SESSION_TYPE.IM_OTHER_INPROGRESS
    | SESSION_TYPE.IM_QUEUE
    | SESSION_TYPE.ROBOT;

type SessionTabValue = {
    type: SessionTabType;
    meta?: string;
};
type TabOption = {
    key: string;
    label: string;
    value: SessionTabValue;
    icon: any;
};

type MoreGroupOption = {
    key: string;
    label: string;
    value: SessionTabValue;
};

const props = defineProps<{
    modelValue: SessionTabValue;
}>();

const emit = defineEmits<{
    (e: "update:modelValue", value: SessionTabValue): void;
}>();

const { t } = useI18n();
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>[]
>([]);
const robotSessionEnabled = ref(0)
const monitorAgentSessionEnabled = ref(0)
const robotGroupExpanded = ref(true);

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

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

const onRobotSessionEnabledUpdated = (value: number) => {
    robotSessionEnabled.value = value;
};

const onMonitorAgentSessionEnabledUpdated = (value: number) => {
    monitorAgentSessionEnabled.value = value;
};

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 primaryTabOptions = computed<TabOption[]>(() => [
    {
        key: SESSION_TYPE.IM + "outer",
        label: t('我的'),
        value: { type: SESSION_TYPE.IM, meta: "outer" },
        icon: servingIcon,
    },
    {
        key: SESSION_TYPE.IM_QUEUE,
        label: t('待分配'),
        value: { type: SESSION_TYPE.IM_QUEUE },
        icon: ringingIcon,
    },
]);

const robotGroupTabs = computed<TabOption[]>(() => [
    {
        key: SESSION_TYPE.ROBOT + "robot",
        label: t('智能体服务中'),
        value: { type: SESSION_TYPE.ROBOT, meta: "robot" },
        icon: robotServingIcon,
    },
    {
        key: SESSION_TYPE.ROBOT + "wait-human",
        label: t('待人工处理'),
        value: { type: SESSION_TYPE.ROBOT, meta: "wait-human" },
        icon: waitHumanIcon,
    },
]);

const visibleTabOptions = computed(() => primaryTabOptions.value);

const showRobotGroup = computed(() => robotSessionEnabled.value !== 0);

const serviceRecordTabValue: SessionTabValue = {
    type: SESSION_TYPE.IM,
    meta: 'service-record',
};

const allMoreGroupOptions = computed<MoreGroupOption[]>(() => [
    {
        key: SESSION_TYPE.IM_OTHER_INPROGRESS,
        label: t('全部会话'),
        value: { type: SESSION_TYPE.IM_OTHER_INPROGRESS },
    },
]);

const visibleMoreGroupOptions = computed(() => {
    if (monitorAgentSessionEnabled.value === 0) {
        return allMoreGroupOptions.value.filter((group) => {
            return group.value.type !== SESSION_TYPE.IM_OTHER_INPROGRESS;
        });
    }

    return allMoreGroupOptions.value;
});

const toggleRobotGroup = () => {
    robotGroupExpanded.value = !robotGroupExpanded.value;
};

const getSessionCount = (key: string) => {
    switch (key) {
        case SESSION_TYPE.IM + "outer":
            return IMSessionList.value.filter((item) => {
                return (
                    item.sessionData.sessionState === "ringing" ||
                    item.sessionData.sessionState === "inProgress" ||
                    item.sessionData.sessionState === "seatJoining"
                );
            }).length;
        case SESSION_TYPE.IM_QUEUE:
            return IMQueueSessionList.value.length;
        case SESSION_TYPE.ROBOT + "robot":
            return IMRobotSessionList.value.filter((item) => {
                return item.sessionData.transToAgentTimes === 0;
            }).length;
        case SESSION_TYPE.ROBOT + "wait-human":
            return IMRobotSessionList.value.filter((item) => {
                return item.sessionData.transToAgentTimes > 0;
            }).length;
        case SESSION_TYPE.IM_OTHER_INPROGRESS:
            return IMOtherInprogressSessionList.value.length;
        default:
            return 0;
    }
};

const isSameTab = (left: SessionTabValue, right: SessionTabValue) =>
    left.type === right.type && left.meta === right.meta;

const handleTabChange = (tab: SessionTabValue) => {
    emit("update:modelValue", tab);
};
</script>

<style scoped>
.tabs-wrapper {
    display: flex;
    align-items: stretch;
    background: #fff;
}

.tabs {
    display: flex;
    padding: 12px 16px;
    background: #fff;
}

.tabs-pc {
    flex-direction: column;
    gap: 12px;
    border-right: 1px solid #f0f0f0;
    min-width: 160px;
}

.tab-item {
    cursor: pointer;
    font-size: 14px;
    color: #000;
    transition: all 0.3s;
    border: none;
    background: transparent;
    white-space: nowrap;
    display: inline-flex;
    align-items: center;
    justify-content: space-between;
    gap: 6px;
    padding: 8px 12px;
    border-radius: 6px;
    text-align: left;
}

.tab-item-sub {
    padding-left: 24px;
}

.tab-group-header {
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 8px 12px;
    color: #000;
    font-size: 14px;
    user-select: none;
}

.tab-group-arrow {
    display: inline-block;
    transition: transform 0.2s;
    font-size: 12px;
}

.tab-group-arrow.collapsed {
    transform: rotate(-90deg);
}

.tab-group-title {
    font-size: 14px;
}

.tab-label {
    min-width: 0;
    font-size: 14px;
    flex: 1;
}

.tab-icon {
    width: 16px;
    height: 16px;
    flex-shrink: 0;
    display: inline-block;
    background-color: currentColor;
    -webkit-mask-repeat: no-repeat;
    mask-repeat: no-repeat;
    -webkit-mask-position: center;
    mask-position: center;
    -webkit-mask-size: contain;
    mask-size: contain;
}

.tab-count {
    margin-left: auto;
    font-size: 14px;
    flex-shrink: 0;
    color: #000;
}

.tab-item.active {
    color: rgb(28, 102, 229);
    font-weight: 400;
    background: rgb(242, 246, 255);
}
</style>
