<script setup>
import { ref, computed, watch } from 'vue'
import { NModal, NButton, NInput, NIcon, NTooltip, NSelect, NCheckbox } from 'naive-ui'
import { CloseOutline, AddOutline, TrashOutline } from '@vicons/ionicons5'
import { translateText } from '../../api/translation'
import { IO_TYPES } from '../../utils/ioInference'
import { normalizeKebabCase, isValidKebabCase } from '../../utils/skillName'

const FIELD_TYPES = IO_TYPES

const props = defineProps({
  show: Boolean,
  skill: Object
})

const emit = defineEmits(['update:show', 'save'])

const form = ref({
  name: '',
  displayName: '',
  description: '',
  canGenerateSkill: false,
  inputs: [],
  outputs: []
})

const isTranslating = ref(false)

watch(() => props.skill, (val) => {
  if (val) {
    form.value = {
      name: val.name || '',
      displayName: val.displayName || '',
      description: val.description || '',
      canGenerateSkill: !!val.canGenerateSkill,
      inputs: (val.inputs || []).map(f => ({ ...f })),
      outputs: (val.outputs || []).map(f => ({ ...f }))
    }
  }
}, { immediate: true })

// ==================== 名称实时校验 ====================
const nameState = computed(() => {
  const raw = form.value.name || ''
  if (!raw.trim()) return { status: 'empty', normalized: '', changed: false }
  const normalized = normalizeKebabCase(raw)
  const valid = isValidKebabCase(normalized)
  if (!valid) return { status: 'invalid', normalized, changed: false }
  if (normalized !== raw) return { status: 'will-normalize', normalized, changed: true }
  return { status: 'valid', normalized, changed: false }
})

/** 检测文本是否为纯英文（不含中文字符） */
function isEnglish(text) {
  if (!text || !text.trim()) return false
  for (let i = 0; i < text.length; i++) {
    const c = text.charCodeAt(i)
    if (c >= 0x4e00 && c <= 0x9fff) return false
  }
  return true
}

const displayNameIsEnglish = computed(() => isEnglish(form.value.displayName))
const descIsEnglish = computed(() => isEnglish(form.value.description))
const hasEnglishField = computed(() => displayNameIsEnglish.value || descIsEnglish.value)

async function handleTranslate() {
  if (isTranslating.value) return
  isTranslating.value = true
  try {
    // 仅翻译 displayName（name 为 kebab-case 标识符，禁止翻译）
    if (displayNameIsEnglish.value) {
      const res = await translateText(form.value.displayName)
      form.value.displayName = res.data || form.value.displayName
    }
    if (descIsEnglish.value) {
      const res = await translateText(form.value.description)
      form.value.description = res.data || form.value.description
    }
  } catch (e) {
    // 翻译失败静默处理
  } finally {
    isTranslating.value = false
  }
}

function addField(list) {
  list.push({ name: '', type: 'string', description: '', required: false })
}

function removeField(list, index) {
  list.splice(index, 1)
}

function handleSave() {
  if (!form.value.name.trim()) {
    alert('请输入技能名称')
    return
  }
  if (nameState.value.status === 'invalid') {
    alert('技能名称规范化后仍非法（需含至少一个字母或数字）')
    return
  }
  // 过滤掉 name 为空的字段
  const data = {
    name: form.value.name,
    displayName: form.value.displayName,
    description: form.value.description,
    canGenerateSkill: !!form.value.canGenerateSkill,
    inputs: form.value.inputs.filter(f => f.name.trim()),
    outputs: form.value.outputs.filter(f => f.name.trim())
  }
  emit('save', data)
}

function closeModal() {
  emit('update:show', false)
}
</script>

<template>
  <n-modal :show="show" @update:show="closeModal" :mask-closable="false">
    <div class="edit-modal">
      <!-- 头部 -->
      <div class="modal-header">
        <h3 class="modal-title">编辑技能</h3>
        <button class="close-btn" @click="closeModal">
          <n-icon size="18">
            <CloseOutline />
          </n-icon>
        </button>
      </div>

      <!-- 表单 -->
      <div class="form-area">
        <div class="form-group">
          <label class="form-label">技能展示名称</label>
          <n-input v-model:value="form.displayName" placeholder="如：军事工作流技能生成器" :maxlength="100" />
        </div>
        <div class="form-group">
          <label class="form-label">
            技能名称
            <span class="label-hint">（kebab-case，唯一标识，禁用大写/空格/下划线/中文）</span>
          </label>
          <n-input v-model:value="form.name" placeholder="如：military-workflow-skill-creator" :maxlength="100" />
          <div v-if="nameState.status === 'will-normalize'" class="name-hint name-warn">
            保存时将自动规范化为：<code>{{ nameState.normalized }}</code>
          </div>
          <div v-else-if="nameState.status === 'invalid'" class="name-hint name-error">
            规范化后仍非法：需含至少一个字母或数字
          </div>
          <div v-else-if="nameState.status === 'valid'" class="name-hint name-ok">
            ✓ 合法 kebab-case
          </div>
        </div>
        <div class="form-group">
          <label class="form-label">技能描述</label>
          <n-input v-model:value="form.description" type="textarea" placeholder="请输入技能描述" :rows="4" :maxlength="500"
            show-count />
        </div>

        <div class="form-group">
          <n-checkbox v-model:checked="form.canGenerateSkill">
            允许此技能生成其他技能（在「技能生成」菜单中可选）
          </n-checkbox>
        </div>

        <!-- 前置数据 -->
        <div class="form-group">
          <div class="section-header">
            <label class="form-label">前置数据</label>
            <n-button size="tiny" quaternary @click="addField(form.inputs)">
              <template #icon><n-icon size="14">
                  <AddOutline />
                </n-icon></template>
              添加
            </n-button>
          </div>
          <div v-if="form.inputs.length" class="io-list">
            <div v-for="(field, i) in form.inputs" :key="'in-' + i" class="io-row">
              <n-input v-model:value="field.name" placeholder="字段名" size="small" style="width: 100px;" />
              <n-select v-model:value="field.type" :options="FIELD_TYPES" size="small" style="width: 100px;" />
              <n-input v-model:value="field.description" placeholder="描述" size="small" style="flex: 1;" />
              <n-checkbox v-model:checked="field.required" size="small">必填</n-checkbox>
              <button class="remove-btn" @click="removeField(form.inputs, i)">
                <n-icon size="14">
                  <TrashOutline />
                </n-icon>
              </button>
            </div>
          </div>
          <div v-else class="io-empty">暂无前置数据</div>
        </div>

        <!-- 输出字段 -->
        <div class="form-group">
          <div class="section-header">
            <label class="form-label">输出字段</label>
            <n-button size="tiny" quaternary @click="addField(form.outputs)">
              <template #icon><n-icon size="14">
                  <AddOutline />
                </n-icon></template>
              添加
            </n-button>
          </div>
          <div v-if="form.outputs.length" class="io-list">
            <div v-for="(field, i) in form.outputs" :key="'out-' + i" class="io-row">
              <n-input v-model:value="field.name" placeholder="字段名" size="small" style="width: 100px;" />
              <n-select v-model:value="field.type" :options="FIELD_TYPES" size="small" style="width: 100px;" />
              <n-input v-model:value="field.description" placeholder="描述" size="small" style="flex: 1;" />
              <n-checkbox v-model:checked="field.required" size="small">必填</n-checkbox>
              <button class="remove-btn" @click="removeField(form.outputs, i)">
                <n-icon size="14">
                  <TrashOutline />
                </n-icon>
              </button>
            </div>
          </div>
          <div v-else class="io-empty">暂无输出字段</div>
        </div>
      </div>

      <!-- 底部按钮 -->
      <div class="modal-footer">
        <n-tooltip v-if="hasEnglishField" placement="top">
          <template #trigger>
            <n-button :loading="isTranslating" @click="handleTranslate" quaternary>
              <template #icon>
                <span style="font-size: 16px;">🌐</span>
              </template>
              翻译为中文
            </n-button>
          </template>
          检测到英文字段，点击翻译为中文
        </n-tooltip>
        <div style="flex: 1;"></div>
        <n-button @click="closeModal" quaternary>
          取消
        </n-button>
        <n-button type="primary" @click="handleSave">
          保存修改
        </n-button>
      </div>
    </div>
  </n-modal>
</template>

<style scoped>
.edit-modal {
  width: 580px;
  max-height: 85vh;
  overflow-y: auto;
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-xl);
  padding: 28px;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.modal-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
}

.close-btn {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: none;
  border: none;
  border-radius: var(--radius-sm);
  color: var(--text-secondary);
  cursor: pointer;
  transition: all var(--transition-fast);
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.05);
  color: var(--text-primary);
}

.form-area {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-label {
  font-size: 13px;
  font-weight: 500;
  color: var(--text-secondary);
}

.label-hint {
  font-size: 11px;
  font-weight: 400;
  color: var(--text-tertiary);
}

.name-hint {
  font-size: 12px;
  margin-top: 2px;
}

.name-hint code {
  background: rgba(255, 255, 255, 0.06);
  padding: 1px 6px;
  border-radius: 3px;
  font-family: 'Consolas', 'Monaco', monospace;
}

.name-warn {
  color: #e0a526;
}

.name-error {
  color: #ef4444;
}

.name-ok {
  color: #22c55e;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.io-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.io-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.io-empty {
  font-size: 12px;
  color: var(--text-tertiary);
  padding: 8px 0;
}

.remove-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  background: none;
  border: none;
  border-radius: var(--radius-sm);
  color: var(--text-secondary);
  cursor: pointer;
  flex-shrink: 0;
  transition: all var(--transition-fast);
}

.remove-btn:hover {
  background: rgba(255, 80, 80, 0.1);
  color: #ff5050;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 12px;
  margin-top: 28px;
}
</style>
