<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { fetchSupportAdmins, transferChat, type SupportAdmin } from '@/api/chats'

const props = defineProps<{
  modelValue: boolean
  conversationId: number
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  success: []
}>()

const visible = ref(false)
const loading = ref(false)
const submitting = ref(false)
const admins = ref<SupportAdmin[]>([])
const selectedAdminId = ref<number | null>(null)

watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    loadAdmins()
  }
})

watch(visible, (val) => {
  emit('update:modelValue', val)
})

async function loadAdmins() {
  loading.value = true
  try {
    admins.value = await fetchSupportAdmins()
  } catch {
    ElMessage.error('加载客服列表失败')
  } finally {
    loading.value = false
  }
}

async function handleSubmit() {
  if (!selectedAdminId.value) {
    ElMessage.warning('请选择目标客服')
    return
  }
  submitting.value = true
  try {
    await transferChat(props.conversationId, selectedAdminId.value)
    ElMessage.success('转接成功')
    visible.value = false
    emit('success')
  } catch {
    ElMessage.error('转接失败')
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <el-dialog v-model="visible" title="转接会话" width="400px">
    <div v-loading="loading" class="transfer-content">
      <p class="tip">选择要转接给的客服：</p>
      <el-radio-group v-model="selectedAdminId" class="admin-list">
        <el-radio
          v-for="admin in admins"
          :key="admin.id"
          :value="admin.id"
          class="admin-item"
        >
          <span class="admin-name">{{ admin.nickname }}</span>
          <span class="admin-count">当前 {{ admin.chat_count }} 个会话</span>
        </el-radio>
      </el-radio-group>
      <el-empty v-if="!loading && admins.length === 0" description="暂无可用客服" />
    </div>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" :loading="submitting" :disabled="!selectedAdminId" @click="handleSubmit">
        确认转接
      </el-button>
    </template>
  </el-dialog>
</template>

<style scoped>
.transfer-content {
  min-height: 100px;
}

.tip {
  margin: 0 0 16px;
  color: #6b7280;
  font-size: 14px;
}

.admin-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  width: 100%;
}

.admin-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: auto;
  padding: 12px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  margin-right: 0;
}

.admin-item.is-checked {
  border-color: #409eff;
  background: #ecf5ff;
}

.admin-name {
  font-weight: 500;
}

.admin-count {
  color: #9ca3af;
  font-size: 13px;
}
</style>
