<template>
  <div class="variable-manager">
    <div class="manager-header">
      <span class="header-title">自定义变量</span>
      <el-button type="primary" size="small" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        添加变量
      </el-button>
    </div>

    <div class="variable-list" v-if="localVariables.length > 0">
      <div
        v-for="(variable, index) in localVariables"
        :key="index"
        class="variable-item"
      >
        <div class="variable-content">
          <div class="variable-name">
            <code>{{ getVarSyntax(variable.name) }}</code>
          </div>
          <div class="variable-info">
            <span class="info-label">默认值:</span>
            <span class="info-value">{{ variable.default_value || '-' }}</span>
          </div>
          <div class="variable-info" v-if="variable.description">
            <span class="info-label">描述:</span>
            <span class="info-value">{{ variable.description }}</span>
          </div>
        </div>
        <div class="variable-actions">
          <el-button type="primary" link size="small" @click="handleEdit(index)">
            <el-icon><Edit /></el-icon>
          </el-button>
          <el-button type="danger" link size="small" @click="handleDelete(index)">
            <el-icon><Delete /></el-icon>
          </el-button>
        </div>
      </div>
    </div>

    <el-empty v-else description="暂无自定义变量" :image-size="80" />

    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑变量' : '添加变量'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="80px">
        <el-form-item label="变量名" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="例如: company_name"
            :disabled="isEdit"
          >
            <template #prepend><span v-text="'{{'"></span></template>
            <template #append><span v-text="'}}'"></span></template>
          </el-input>
          <div class="form-tip">只能包含字母、数字和下划线</div>
        </el-form-item>
        <el-form-item label="默认值" prop="default_value">
          <el-input
            v-model="formData.default_value"
            placeholder="请输入默认值"
            type="textarea"
            :rows="2"
          />
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="formData.description"
            placeholder="请输入变量描述（可选）"
            type="textarea"
            :rows="2"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import type { PromptVariable } from '@/types/prompt-template'

const props = defineProps<{
  modelValue: PromptVariable[]
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: PromptVariable[]): void
  (e: 'insert', varName: string): void
}>()

const localVariables = ref<PromptVariable[]>([...props.modelValue])
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentIndex = ref(-1)
const formRef = ref()

const formData = ref<PromptVariable>({
  name: '',
  default_value: '',
  description: ''
})

const validateVarName = (rule: any, value: string, callback: any) => {
  if (!value) {
    callback(new Error('请输入变量名'))
    return
  }
  if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(value)) {
    callback(new Error('变量名只能包含字母、数字和下划线，且不能以数字开头'))
    return
  }
  const exists = localVariables.value.some(
    (v, idx) => v.name === value && idx !== currentIndex.value
  )
  if (exists) {
    callback(new Error('变量名已存在'))
    return
  }
  callback()
}

const formRules = {
  name: [{ required: true, validator: validateVarName, trigger: 'blur' }],
  default_value: [{ required: true, message: '请输入默认值', trigger: 'blur' }]
}

const getVarSyntax = (name: string) => {
  return `{{${name}}}`
}

const handleAdd = () => {
  isEdit.value = false
  currentIndex.value = -1
  formData.value = {
    name: '',
    default_value: '',
    description: ''
  }
  dialogVisible.value = true
}

const handleEdit = (index: number) => {
  isEdit.value = true
  currentIndex.value = index
  formData.value = { ...localVariables.value[index] }
  dialogVisible.value = true
}

const handleDelete = (index: number) => {
  localVariables.value.splice(index, 1)
  emit('update:modelValue', localVariables.value)
  ElMessage.success('删除成功')
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
  } catch {
    return
  }

  if (isEdit.value) {
    localVariables.value[currentIndex.value] = { ...formData.value }
    ElMessage.success('修改成功')
  } else {
    localVariables.value.push({ ...formData.value })
    ElMessage.success('添加成功')
  }

  emit('update:modelValue', localVariables.value)
  dialogVisible.value = false
}

watch(
  () => props.modelValue,
  (newVal) => {
    localVariables.value = [...newVal]
  },
  { deep: true }
)
</script>

<style scoped>
.variable-manager {
  border: 1px solid var(--el-border-color-light);
  border-radius: 6px;
  overflow: hidden;
}

.manager-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: var(--el-fill-color-light);
  border-bottom: 1px solid var(--el-border-color-light);
}

.header-title {
  font-size: 14px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.variable-list {
  max-height: 300px;
  overflow-y: auto;
}

.variable-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 12px 16px;
  border-bottom: 1px solid var(--el-border-color-extra-light);
  transition: background-color 0.2s;
}

.variable-item:last-child {
  border-bottom: none;
}

.variable-item:hover {
  background-color: var(--el-fill-color-extra-light);
}

.variable-content {
  flex: 1;
  min-width: 0;
}

.variable-name {
  margin-bottom: 6px;
}

.variable-name code {
  font-family: monospace;
  font-size: 13px;
  color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
  padding: 2px 6px;
  border-radius: 3px;
}

.variable-info {
  display: flex;
  gap: 8px;
  margin-bottom: 4px;
  font-size: 12px;
}

.info-label {
  color: var(--el-text-color-secondary);
  flex-shrink: 0;
}

.info-value {
  color: var(--el-text-color-regular);
  word-break: break-all;
}

.variable-actions {
  display: flex;
  gap: 4px;
  margin-left: 12px;
}

.form-tip {
  font-size: 12px;
  color: var(--el-text-color-placeholder);
  margin-top: 4px;
}
</style>
