<template>
  <a-modal
    :open="open"
    :width="640"
    :ok-text="okText"
    :ok-button-props="{ disabled: !canSubmit, type: 'primary' }"
    :confirm-loading="submitting"
    cancel-text="取消"
    class="board-meeting-modal"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <template #title>
      <span class="board-meeting-modal__title">
        <BankOutlined class="board-meeting-modal__title-icon" />
        发起私董会
      </span>
    </template>
    <div class="board-modal">
      <!-- 讨论主题 -->
      <div class="board-modal__field">
        <label class="board-modal__label">
          讨论主题 <span class="board-modal__required">*</span>
        </label>
        <a-textarea
          v-model:value="topic"
          :auto-size="{ minRows: 2, maxRows: 4 }"
          placeholder="例如：是否应该投入资源做这个功能？"
          :disabled="submitting"
        />
      </div>

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

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

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

        <div v-else class="board-modal__experts">
          <div
            v-for="expert in experts"
            :key="expert.name"
            class="board-modal__expert-card"
            :class="{
              'board-modal__expert-card--selected': isSelected(expert.name),
              'board-modal__expert-card--moderator': isModerator(expert.name),
            }"
            @click="toggleExpert(expert.name)"
          >
            <div class="board-modal__expert-header">
              <span
              class="board-modal__expert-avatar"
              :class="{ 'board-modal__expert-avatar--moderator': isModerator(expert.name) }"
            >{{ expert.avatar }}</span>
              <span class="board-modal__expert-name">{{ expert.name }}</span>
              <span v-if="isModerator(expert.name)" class="board-modal__tag board-modal__tag--moderator">主持人</span>
              <span v-else-if="isSelected(expert.name)" class="board-modal__tag board-modal__tag--selected">
                #{{ selectedOrder(expert.name) }}
              </span>
            </div>
            <div class="board-modal__expert-persona">
              {{ truncate(expert.persona, 80) }}
            </div>
            <div v-if="expert.decision_framework" class="board-modal__expert-framework">
              <ThunderboltOutlined /> {{ expert.decision_framework }}
            </div>
          </div>
        </div>
      </div>

      <!-- 最大轮次 -->
      <div class="board-modal__field">
        <label class="board-modal__label">最大讨论轮次</label>
        <div class="board-modal__rounds">
          <a-slider
            v-model:value="maxRounds"
            :min="1"
            :max="10"
            :marks="{ 1: '1', 3: '3', 5: '5', 10: '10' }"
            :disabled="submitting"
            class="board-modal__rounds-slider"
          />
          <a-input-number
            v-model:value="maxRounds"
            :min="1"
            :max="10"
            :disabled="submitting"
            class="board-modal__rounds-input"
          />
        </div>
      </div>

      <!-- 预览 -->
      <div v-if="previewCommand" class="board-modal__preview">
        <div class="board-modal__preview-label">将发送：</div>
        <code class="board-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,
  Slider as ASlider,
  InputNumber as AInputNumber,
  message,
} from 'ant-design-vue'
import { ThunderboltOutlined, BankOutlined } 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 topic = ref('')
const selectedExperts = ref<string[]>([])
const maxRounds = ref(5)
const experts = ref<IExpertTemplate[]>([])
const loading = ref(false)
const submitting = ref(false)

const simpleImage = AEmpty.PRESENTED_IMAGE_SIMPLE

const canSubmit = computed(() => {
  return topic.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 trimmedTopic = topic.value.trim()
  return `@board:${expertList} rounds=${maxRounds.value} ${trimmedTopic}`
})

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)
    message.error('专家列表加载失败，请稍后重试')
    experts.value = []
  } finally {
    loading.value = false
  }
}

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

function isModerator(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 the constructed @board command; the parent sends it via the normal chat pipeline
  emit('submit', previewCommand.value)
  // Close after a short tick to let the parent process the send
  setTimeout(() => {
    submitting.value = false
    resetForm()
    emit('update:open', false)
  }, 50)
}

function handleCancel(): void {
  if (submitting.value) return
  resetForm()
  emit('update:open', false)
}

function resetForm(): void {
  topic.value = ''
  selectedExperts.value = []
  maxRounds.value = 5
}

// Load experts when modal opens
watch(
  () => props.open,
  (newOpen) => {
    if (newOpen) {
      loadExperts()
    }
  }
)
</script>

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

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

.board-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);
}

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

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

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

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

.board-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);
}

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

.board-modal__expert-card--selected {
  background: var(--accent-board-bg);
  border-color: var(--accent-board);
  border-width: 2px;
}

.board-modal__expert-card--moderator {
  background: var(--accent-board-soft);
}

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

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

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

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

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

.board-modal__tag {
  display: inline-flex;
  align-items: center;
  height: 20px;
  padding: 0 6px;
  font-size: var(--font-xs);
  border-radius: var(--radius-sm);
  line-height: 1;
}

.board-modal__tag--moderator {
  background: var(--accent-board);
  color: var(--text-inverse);
}

.board-modal__tag--selected {
  background: var(--accent-board-soft);
  color: var(--accent-board);
}

.board-modal__rounds {
  display: flex;
  align-items: center;
}

.board-modal__rounds-slider {
  flex: 1;
}

.board-modal__rounds-input {
  margin-left: 16px;
  width: 80px;
}

.board-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);
}

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

.board-modal__preview-code {
  font-family: var(--font-mono);
  font-size: var(--font-xs);
  color: var(--accent-board);
  word-break: break-all;
  display: block;
}

.board-modal__expert-avatar--moderator {
  background: var(--accent-board-soft);
  border-radius: var(--radius-full);
  padding: 2px;
}

/* ── Modal-level VI overrides ── */
.board-meeting-modal__title {
  display: inline-flex;
  align-items: center;
  gap: var(--space-2);
  font-weight: var(--font-weight-semibold);
  color: var(--text-primary);
}

.board-meeting-modal__title-icon {
  color: var(--accent-board);
}

:deep(.ant-modal-header) {
  border-bottom: 1px solid var(--border-color);
}

:deep(.ant-modal-title) {
  font-weight: var(--font-weight-semibold);
}

:deep(.ant-btn-primary) {
  background: var(--accent-board);
  border-color: var(--accent-board);
}

:deep(.ant-btn-primary:hover),
:deep(.ant-btn-primary:focus) {
  background: var(--accent-board-hover);
  border-color: var(--accent-board-hover);
}

:deep(.ant-btn-primary:disabled) {
  background: var(--color-gray-300);
  border-color: var(--color-gray-300);
  color: var(--text-inverse);
}

:deep(.ant-input:focus),
:deep(.ant-input-focused) {
  border-color: var(--accent-board);
  box-shadow: 0 0 0 2px var(--accent-board-soft);
}

:deep(.ant-input-number-focused),
:deep(.ant-input-number:focus-within) {
  border-color: var(--accent-board);
  box-shadow: 0 0 0 2px var(--accent-board-soft);
}

:deep(.ant-input-number-input:focus) {
  border-color: var(--accent-board);
}

:deep(.ant-slider-track) {
  background: var(--accent-board) !important;
}

:deep(.ant-slider-handle) {
  border-color: var(--accent-board);
}

:deep(.ant-slider-handle:focus) {
  border-color: var(--accent-board-hover);
  box-shadow: 0 0 0 4px var(--accent-board-soft);
}
</style>
