<template>
    <t-dialog class="pc-blacklist-add-dialog" v-model:visible="addDialogVisible" :close-on-overlay-click="false"
        :header="t('添加用户至黑名单')" :footer="true" width="640px" @close="closeAddDialog">
        <template #body>
            <div class="pc-blacklist-body">
                <div class="pc-blacklist-section">
                    <div class="pc-blacklist-label">{{ t('用户名') }}</div>
                    <div class="pc-blacklist-username">{{ userDisplayName }}</div>
                </div>

                <div class="pc-blacklist-section">
                    <div class="pc-blacklist-label">{{ t('拉黑持续时间') }}</div>
                    <div class="pc-blacklist-radio-group">
                        <label v-for="option in durationOptions" :key="option.value" class="pc-blacklist-radio">
                            <input type="radio" class="pc-blacklist-radio-input" :value="option.value"
                                :checked="draft.durationType === option.value" @change="selectDuration(option.value)" />
                            <span class="pc-blacklist-radio-dot" />
                            <span class="pc-blacklist-radio-label">{{ option.label }}</span>
                        </label>
                    </div>
                </div>

                <div v-if="isCustomDuration" class="pc-blacklist-section pc-blacklist-section--custom">
                    <div class="pc-blacklist-label pc-blacklist-label--small">{{ t('拉黑时间范围') }}</div>
                    <t-date-range-picker v-model="customRangeValue" allow-input clearable enable-time-picker
                        format="YYYY-MM-DD HH:mm:ss" value-type="YYYY-MM-DD HH:mm:ss"
                        @change="handleCustomRangeChange" />
                </div>

                <div class="pc-blacklist-section">
                    <div class="pc-blacklist-label">{{ t('拉黑后的功能限制') }}</div>
                    <div class="pc-blacklist-radio-group">
                        <label v-for="option in blockTypeOptions" :key="option.value" class="pc-blacklist-radio">
                            <input type="radio" class="pc-blacklist-radio-input" :value="option.value"
                                :checked="draft.blockType === option.value" @change="selectBlockType(option.value)" />
                            <span class="pc-blacklist-radio-dot" />
                            <span class="pc-blacklist-radio-label">{{ option.label }}</span>
                        </label>
                    </div>
                </div>

                <div class="pc-blacklist-section">
                    <div class="pc-blacklist-label">{{ t('拉黑原因') }}</div>
                    <div class="pc-blacklist-textarea-wrap">
                        <textarea v-model="draft.reason" class="pc-blacklist-textarea" maxlength="200"
                            :placeholder="t('请输入')" />
                        <div class="pc-blacklist-textarea-counter">{{ reasonLength }}/200</div>
                    </div>
                </div>
            </div>
        </template>

        <template #footer>
            <div class="pc-blacklist-footer">
                <button type="button" class="pc-blacklist-button pc-blacklist-button--confirm"
                    @click="handleAddConfirm">
                    {{ t('加入黑名单') }}
                </button>
                <button type="button" class="pc-blacklist-button pc-blacklist-button--cancel" @click="closeAddDialog">
                    {{ t('取消') }}
                </button>
            </div>
        </template>
    </t-dialog>

    <t-dialog class="pc-blacklist-remove-dialog" v-model:visible="removeDialogVisible" :close-on-overlay-click="true"
        :header="t('移出黑名单')" :footer="true" width="480px" @close="closeRemoveDialog">
        <template #body>
            <div class="pc-blacklist-remove-body">{{ t('确认要解除当前用户的拉黑状态吗？') }}</div>
        </template>
        <template #footer>
            <div class="pc-blacklist-footer">
                <button type="button" class="pc-blacklist-button pc-blacklist-button--confirm"
                    @click="handleRemoveConfirm">
                    {{ t('确定') }}
                </button>
                <button type="button" class="pc-blacklist-button pc-blacklist-button--cancel"
                    @click="closeRemoveDialog">
                    {{ t('取消') }}
                </button>
            </div>
        </template>
    </t-dialog>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import dayjs from 'dayjs';
import AIDeskCoreInstance, { SESSION_TYPE, type SessionTypeMap } from '@tencentcloud/ai-desk-core';
import toast from '../../../../utils/toast';

type DurationValue = '10m' | '1h' | '1d' | '7d' | 'custom';
type BlockTypeValue = 1 | 2;

const props = defineProps<{
    mode: 'add' | 'remove' | null;
    session: SessionTypeMap[SESSION_TYPE] | null;
}>();

const emit = defineEmits<{
    (event: 'update:mode', value: 'add' | 'remove' | null): void;
    (event: 'success'): void;
}>();

const { t } = useI18n();

const addDialogVisible = ref(false);
const removeDialogVisible = ref(false);

const durationOptions = computed<Array<{ label: string; value: DurationValue }>>(() => [
    { label: t('10 分钟'), value: '10m' },
    { label: t('1 小时'), value: '1h' },
    { label: t('1 天'), value: '1d' },
    { label: t('7 天'), value: '7d' },
    { label: t('自定义'), value: 'custom' },
]);

const blockTypeOptions = computed<Array<{ label: string; value: BlockTypeValue }>>(() => [
    { label: t('仅禁止使用人工服务'), value: 1 },
    { label: t('禁止使用机器人与人工服务'), value: 2 },
]);

const getPresetEndTime = (startTime: number, durationType: Exclude<DurationValue, 'custom'>) => {
    const start = dayjs.unix(startTime);
    switch (durationType) {
        case '10m':
            return start.add(10, 'minute').unix();
        case '1h':
            return start.add(1, 'hour').unix();
        case '1d':
            return start.add(1, 'day').unix();
        case '7d':
            return start.add(7, 'day').unix();
        default:
            return startTime;
    }
};

const createDefaultDraft = () => {
    const startTime = dayjs().unix();
    return {
        durationType: '10m' as DurationValue,
        startTime,
        endTime: getPresetEndTime(startTime, '10m'),
        blockType: 1 as BlockTypeValue,
        reason: '',
    };
};

const draft = ref(createDefaultDraft());
const customRangeValue = ref<[string, string]>(['', '']);

const isCustomDuration = computed(() => draft.value.durationType === 'custom');

const reasonLength = computed(() => draft.value.reason.length);

const userDisplayName = computed(() => {
    const session = props.session;
    if (!session) return '-';
    return session.nickname || session.userId || '-';
});

const syncCustomInputsFromDraft = () => {
    customRangeValue.value = [
        dayjs(draft.value.startTime * 1000).format('YYYY-MM-DD HH:mm:ss'),
        dayjs(draft.value.endTime * 1000).format('YYYY-MM-DD HH:mm:ss'),
    ];
};

const selectDuration = (value: DurationValue) => {
    draft.value.durationType = value;
    if (value === 'custom') {
        syncCustomInputsFromDraft();
        return;
    }
    const currentTimestamp = dayjs().unix();
    draft.value.startTime = currentTimestamp;
    draft.value.endTime = getPresetEndTime(currentTimestamp, value);
};

const selectBlockType = (value: BlockTypeValue) => {
    draft.value.blockType = value;
};

const handleCustomRangeChange = (value: [string, string] | undefined | null) => {
    if (!value || value.length !== 2) return;
    const [start, end] = value;
    if (start) {
        const startUnix = dayjs(start).unix();
        if (!Number.isNaN(startUnix)) draft.value.startTime = startUnix;
    }
    if (end) {
        const endUnix = dayjs(end).unix();
        if (!Number.isNaN(endUnix)) draft.value.endTime = endUnix;
    }
};

const closeAddDialog = () => {
    addDialogVisible.value = false;
    emit('update:mode', null);
};

const closeRemoveDialog = () => {
    removeDialogVisible.value = false;
    emit('update:mode', null);
};

const handleAddConfirm = async () => {
    const session = props.session;
    if (!session?.userId) {
        return;
    }

    if (draft.value.durationType !== 'custom') {
        const currentTimestamp = dayjs().unix();
        draft.value.startTime = currentTimestamp;
        draft.value.endTime = getPresetEndTime(currentTimestamp, draft.value.durationType);
    }

    if (draft.value.endTime <= draft.value.startTime) {
        return toast.error(t('拉黑结束时间必须晚于开始时间'));
    }

    try {
        await AIDeskCoreInstance.sessionService.addBlacklist({
            userId: session.userId,
            beginTime: draft.value.startTime,
            endTime: draft.value.endTime,
            blockType: draft.value.blockType,
            reason: draft.value.reason.trim(),
        });
        emit('success');
        closeAddDialog();
    } catch (error) {
        console.error(error);
        toast.error(t('拉黑失败'));
    }
};

const handleRemoveConfirm = async () => {
    const session = props.session;
    if (!session?.userId) {
        closeRemoveDialog();
        return;
    }
    try {
        await AIDeskCoreInstance.sessionService.removeBlacklist({ userId: session.userId });
        emit('success');
        closeRemoveDialog();
    } catch (error) {
        console.error(error);
        toast.error(t('解除拉黑失败'));
    }
};

watch(
    () => props.mode,
    (mode) => {
        if (mode === 'add') {
            draft.value = createDefaultDraft();
            syncCustomInputsFromDraft();
            addDialogVisible.value = true;
            removeDialogVisible.value = false;
        } else if (mode === 'remove') {
            removeDialogVisible.value = true;
            addDialogVisible.value = false;
        } else {
            addDialogVisible.value = false;
            removeDialogVisible.value = false;
        }
    },
    { immediate: true },
);
</script>

<style scoped>
.pc-blacklist-body {
    padding: 0 4px;
}

.pc-blacklist-section+.pc-blacklist-section {
    margin-top: 20px;
}

.pc-blacklist-section--custom {
    margin-top: 12px;
}

.pc-blacklist-label {
    font-size: 14px;
    line-height: 22px;
    color: #86909c;
    margin-bottom: 8px;
}

.pc-blacklist-label--small {
    font-size: 13px;
    margin-bottom: 6px;
}

.pc-blacklist-username {
    font-size: 14px;
    line-height: 22px;
    color: #1d2129;
}

.pc-blacklist-radio-group {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 24px;
}

.pc-blacklist-radio {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    cursor: pointer;
    font-size: 14px;
    line-height: 22px;
    color: #1d2129;
    user-select: none;
}

.pc-blacklist-radio-input {
    position: absolute;
    width: 0;
    height: 0;
    opacity: 0;
    pointer-events: none;
}

.pc-blacklist-radio-dot {
    width: 16px;
    height: 16px;
    border-radius: 50%;
    border: 1px solid #c9cdd4;
    background: #fff;
    box-sizing: border-box;
    display: inline-block;
    position: relative;
    flex-shrink: 0;
    transition: border-color 0.15s, background 0.15s;
}

.pc-blacklist-radio-input:checked+.pc-blacklist-radio-dot {
    border-color: #316EF5;
    background: #316EF5;
}

.pc-blacklist-radio-input:checked+.pc-blacklist-radio-dot::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background: #fff;
    transform: translate(-50%, -50%);
}

.pc-blacklist-custom-row {
    display: flex;
    gap: 16px;
}

.pc-blacklist-custom-item {
    flex: 1;
    min-width: 0;
}

.pc-blacklist-textarea-wrap {
    position: relative;
}

.pc-blacklist-textarea {
    width: 100%;
    min-height: 88px;
    padding: 8px 12px 24px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    background: #fff;
    font-size: 14px;
    line-height: 22px;
    color: #1d2129;
    resize: vertical;
    box-sizing: border-box;
    outline: none;
    transition: border-color 0.15s;
}

.pc-blacklist-textarea:focus {
    border-color: #316EF5;
}

.pc-blacklist-textarea::placeholder {
    color: #b0b6bf;
}

.pc-blacklist-textarea-counter {
    position: absolute;
    right: 12px;
    bottom: 8px;
    font-size: 12px;
    line-height: 18px;
    color: #a5a9b0;
    pointer-events: none;
}

.pc-blacklist-footer {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 16px;
    padding: 8px 0 4px;
}

.pc-blacklist-button {
    min-width: 120px;
    height: 40px;
    padding: 0 32px;
    border-radius: 999px;
    font-size: 14px;
    line-height: 20px;
    cursor: pointer;
    border: 1px solid transparent;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    box-sizing: border-box;
    transition: background 0.15s, color 0.15s, border-color 0.15s;
}

.pc-blacklist-button--cancel {
    background: #fff;
    color: #1d2129;
    border-color: #d9d9d9;
}

.pc-blacklist-button--cancel:hover {
    border-color: #316EF5;
    color: #316EF5;
}

.pc-blacklist-button--confirm {
    background: #316EF5;
    color: #fff;
    border-color: #316EF5;
}

.pc-blacklist-button--confirm:hover {
    background: #2A5FDB;
    border-color: #2A5FDB;
}

.pc-blacklist-remove-body {
    padding: 4px 0 8px;
    font-size: 14px;
    line-height: 22px;
    color: #1d2129;
}
</style>

<style>
/* 非 scoped：覆盖 TDesign Dialog teleport 出去的样式 */
.pc-blacklist-add-dialog .t-dialog__header,
.pc-blacklist-remove-dialog .t-dialog__header,
.pc-blacklist-add-dialog .t-dialog__body,
.pc-blacklist-remove-dialog .t-dialog__body {
    text-align: left !important;
}

.pc-blacklist-add-dialog .t-dialog__footer,
.pc-blacklist-remove-dialog .t-dialog__footer {
    text-align: center !important;
    padding: 0 0 16px !important;
}

.pc-blacklist-add-dialog .t-dialog__footer .t-button+.t-button,
.pc-blacklist-remove-dialog .t-dialog__footer .t-button+.t-button {
    margin-left: 0 !important;
}
</style>
