<template>
  <a-modal
    :open="open"
    title="组建专家团"
    :width="640"
    :ok-text="okText"
    :ok-button-props="{ disabled: !canSubmit }"
    :confirm-loading="submitting"
    cancel-text="取消"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <div class="team-modal">
      <!-- 任务描述 -->
      <div class="team-modal__field">
        <label class="team-modal__label">
          任务描述 <span class="team-modal__required">*</span>
        </label>
        <a-textarea
          v-model:value="task"
          :auto-size="{ minRows: 2, maxRows: 4 }"
          placeholder="例如：帮我设计一个电商订单模块"
          :disabled="submitting"
        />
      </div>

      <!-- 选择专家 -->
      <div class="team-modal__field">
        <label class="team-modal__label">
          选择专家 <span class="team-modal__required">*</span>
          <span class="team-modal__hint">（已选 {{ selectedExperts.length }} / {{ MAX_EXPERTS }}，首位为 Lead）</span>
        </label>

        <div v-if="loading" class="team-modal__loading">
          <a-spin size="small" /> 加载专家列表...
        </div>

        <div v-else-if="experts.length === 0" class="team-modal__empty">
          <a-empty description="未找到可用专家模板" :image="simpleImage" />
        </div>

        <div v-else class="team-modal__experts">
          <div
            v-for="expert in experts"
            :key="expert.name"
            class="team-modal__expert-card"
            :class="{
              'team-modal__expert-card--selected': isSelected(expert.name),
              'team-modal__expert-card--lead': isLead(expert.name),
            }"
            :style="isSelected(expert.name) ? { borderColor: expert.color } : {}"
            @click="toggleExpert(expert.name)"
          >
            <div class="team-modal__expert-header">
              <span class="team-modal__expert-avatar">{{ expert.avatar }}</span>
              <span class="team-modal__expert-name">{{ expert.name }}</span>
              <a-tag v-if="isLead(expert.name)" color="blue" size="small">Lead</a-tag>
              <a-tag v-else-if="isSelected(expert.name)" color="green" size="small">
                #{{ selectedOrder(expert.name) }}
              </a-tag>
            </div>
            <div class="team-modal__expert-persona">
              {{ truncate(expert.persona, 80) }}
            </div>
            <div v-if="expert.decision_framework" class="team-modal__expert-framework">
              <ThunderboltOutlined /> {{ expert.decision_framework }}
            </div>
          </div>
        </div>
      </div>

      <!-- 预览 -->
      <div v-if="previewCommand" class="team-modal__preview">
        <div class="team-modal__preview-label">将发送：</div>
        <code class="team-modal__preview-code">{{ previewCommand }}</code>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import {
  Modal as AModal,
  Textarea as ATextarea,
  Spin as ASpin,
  Empty as AEmpty,
  Tag as ATag,
} from 'ant-design-vue'
import { ThunderboltOutlined } from '@ant-design/icons-vue'
import { apiClient } from '@/api/client'
import type { IExpertTemplate } from '@/api/types'

const MAX_EXPERTS = 10

interface IProps {
  open: boolean
}

const props = defineProps<IProps>()

const emit = defineEmits<{
  'update:open': [value: boolean]
  submit: [command: string]
}>()

const task = ref('')
const selectedExperts = ref<string[]>([])
const experts = ref<IExpertTemplate[]>([])
const loading = ref(false)
const submitting = ref(false)

const simpleImage = AEmpty.PRESENTED_IMAGE_SIMPLE

const canSubmit = computed(() => {
  return task.value.trim().length > 0 && selectedExperts.value.length >= 1
})

const okText = computed(() => {
  if (!canSubmit.value) return '组建专家团'
  return `组建专家团（${selectedExperts.value.length} 位专家）`
})

const previewCommand = computed(() => {
  if (!canSubmit.value) return ''
  const expertList = selectedExperts.value.join(',')
  const trimmedTask = task.value.trim()
  return `@team:${expertList} ${trimmedTask}`
})

async function loadExperts(): Promise<void> {
  loading.value = true
  try {
    const data = await apiClient.getExperts()
    experts.value = data.experts || []
  } catch (error) {
    console.error('Failed to load experts:', error)
    experts.value = []
  } finally {
    loading.value = false
  }
}

function isSelected(name: string): boolean {
  return selectedExperts.value.includes(name)
}

function isLead(name: string): boolean {
  return selectedExperts.value[0] === name
}

function selectedOrder(name: string): number {
  const idx = selectedExperts.value.indexOf(name)
  return idx + 1
}

function toggleExpert(name: string): void {
  if (submitting.value) return
  const idx = selectedExperts.value.indexOf(name)
  if (idx === -1) {
    if (selectedExperts.value.length >= MAX_EXPERTS) return
    selectedExperts.value.push(name)
  } else {
    selectedExperts.value.splice(idx, 1)
  }
}

function truncate(text: string, max: number): string {
  if (!text) return ''
  const cleaned = text.replace(/\s+/g, ' ').trim()
  return cleaned.length > max ? cleaned.slice(0, max) + '...' : cleaned
}

function handleSubmit(): void {
  if (!canSubmit.value) return
  submitting.value = true
  emit('submit', previewCommand.value)
  setTimeout(() => {
    submitting.value = false
    resetForm()
    emit('update:open', false)
  }, 50)
}

function handleCancel(): void {
  resetForm()
  emit('update:open', false)
}

function resetForm(): void {
  task.value = ''
  selectedExperts.value = []
}

watch(
  () => props.open,
  (newOpen) => {
    if (newOpen) {
      loadExperts()
    }
  }
)
</script>

<style scoped>
.team-modal {
  display: flex;
  flex-direction: column;
  gap: var(--space-4);
}

.team-modal__field {
  display: flex;
  flex-direction: column;
  gap: var(--space-2);
}

.team-modal__label {
  font-weight: var(--font-weight-semibold);
  font-size: var(--font-sm);
  color: var(--text-primary);
  display: flex;
  align-items: center;
  gap: var(--space-1);
}

.team-modal__required {
  color: var(--color-error);
}

.team-modal__hint {
  font-weight: var(--font-weight-normal);
  font-size: var(--font-xs);
  color: var(--text-tertiary);
}

.team-modal__loading,
.team-modal__empty {
  padding: var(--space-4);
  text-align: center;
  color: var(--text-tertiary);
}

.team-modal__experts {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: var(--space-2);
  max-height: 280px;
  overflow-y: auto;
  padding: var(--space-1);
}

.team-modal__expert-card {
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding: var(--space-2) var(--space-3);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  cursor: pointer;
  transition: all var(--transition-fast);
  background: var(--bg-primary);
}

.team-modal__expert-card:hover {
  border-color: var(--color-primary);
  background: var(--bg-secondary, var(--bg-primary));
}

.team-modal__expert-card--selected {
  background: rgba(59, 130, 246, 0.04);
  border-width: 2px;
}

.team-modal__expert-card--lead {
  background: rgba(59, 130, 246, 0.06);
}

.team-modal__expert-header {
  display: flex;
  align-items: center;
  gap: 6px;
}

.team-modal__expert-avatar {
  font-size: 20px;
}

.team-modal__expert-name {
  font-weight: var(--font-weight-semibold);
  font-size: var(--font-sm);
  color: var(--text-primary);
  flex: 1;
}

.team-modal__expert-persona {
  font-size: var(--font-xs);
  color: var(--text-secondary);
  line-height: 1.4;
}

.team-modal__expert-framework {
  font-size: var(--font-xs);
  color: var(--text-tertiary);
  display: flex;
  align-items: center;
  gap: 4px;
}

.team-modal__preview {
  padding: var(--space-2) var(--space-3);
  background: var(--bg-secondary, var(--bg-primary));
  border: 1px dashed var(--border-color);
  border-radius: var(--radius-md);
}

.team-modal__preview-label {
  font-size: var(--font-xs);
  color: var(--text-tertiary);
  margin-bottom: 4px;
}

.team-modal__preview-code {
  font-family: 'SF Mono', Monaco, Consolas, monospace;
  font-size: var(--font-xs);
  color: var(--color-primary);
  word-break: break-all;
  display: block;
}
</style>
