<script setup>
import { ref, reactive, computed, h, onMounted } from 'vue'
import {
  NIcon, NDataTable, NForm, NFormItem, NInput,
  NSwitch, NSpace, NTag, NButton, NTooltip, NModal,
  NPopconfirm, useMessage
} from 'naive-ui'
import {
  AddOutline, CreateOutline, TrashOutline, CopyOutline, ReloadOutline, WarningOutline
} from '@vicons/ionicons5'
import {
  getHermesErrorPatterns, createHermesErrorPattern, updateHermesErrorPattern,
  deleteHermesErrorPattern, toggleHermesErrorPattern, resetHermesErrorPatterns
} from '../../api/hermesError'

const message = useMessage()

const loading = ref(false)
const patterns = ref([])
const saving = ref(false)

// 弹窗
const showModal = ref(false)
const editingId = ref(null)
const isBuiltin = ref(false)
const form = reactive({
  name: '',
  pattern: '',
  description: '',
  enabled: true
})

const stats = computed(() => ({
  total: patterns.value.length,
  enabled: patterns.value.filter(p => p.enabled).length,
  builtin: patterns.value.filter(p => p.isBuiltIn).length
}))

const columns = [
  {
    title: '启用', key: 'enabled', width: 70,
    render: (row) => h(NSwitch, {
      size: 'small',
      value: !!row.enabled,
      loading: row._toggling,
      onUpdateValue: (v) => handleToggle(row, v)
    })
  },
  {
    title: '名称', key: 'name', width: 200,
    render: (row) => h('span', { style: 'font-weight: 500' }, row.name)
  },
  {
    title: '匹配模式', key: 'pattern', width: 220,
    render: (row) => h('code', {
      style: 'padding: 2px 6px; background: rgba(127,127,127,0.12); border-radius: 3px; font-size: 12px;'
    }, row.pattern)
  },
  { title: '说明', key: 'description', ellipsis: { tooltip: true } },
  {
    title: '类型', key: 'isBuiltIn', width: 90,
    render: (row) => row.isBuiltIn
      ? h(NTag, { type: 'info', size: 'small', variant: 'bordered' }, { default: () => '内置' })
      : h(NTag, { type: 'success', size: 'small', variant: 'bordered' }, { default: () => '自定义' })
  },
  {
    title: '操作', key: 'actions', width: 140,
    render: (row) => h(NSpace, { size: 2, align: 'center', wrap: false }, {
      default: () => [
        h(NTooltip, null, {
          trigger: () => h(NButton, {
            size: 'tiny', quaternary: true, circle: true,
            onClick: () => handleEdit(row)
          }, { icon: () => h(NIcon, { size: 16 }, { default: () => h(CreateOutline) }) }),
          default: () => '编辑'
        }),
        h(NTooltip, null, {
          trigger: () => h(NButton, {
            size: 'tiny', quaternary: true, circle: true,
            onClick: () => handleDuplicate(row)
          }, { icon: () => h(NIcon, { size: 16 }, { default: () => h(CopyOutline) }) }),
          default: () => '复制为自定义'
        }),
        // 内置不可删除，自定义可删除
        row.isBuiltIn
          ? h(NTooltip, null, {
              trigger: () => h(NButton, {
                size: 'tiny', quaternary: true, circle: true, disabled: true
              }, { icon: () => h(NIcon, { size: 16 }, { default: () => h(TrashOutline) }) }),
              default: () => '内置模式不可删除'
            })
          : h(NPopconfirm, {
              onPositiveClick: () => handleDelete(row),
              positiveText: '确定',
              negativeText: '取消'
            }, {
              trigger: () => h(NButton, {
                size: 'tiny', quaternary: true, circle: true, type: 'error'
              }, { icon: () => h(NIcon, { size: 16 }, { default: () => h(TrashOutline) }) }),
              default: () => `确认删除模式「${row.name}」？`
            })
      ]
    })
  }
]

async function loadPatterns() {
  loading.value = true
  try {
    const res = await getHermesErrorPatterns()
    patterns.value = (res.data || []).map(p => ({ ...p, _toggling: false }))
  } catch (e) {
    message.error(e.message || '加载失败')
  } finally {
    loading.value = false
  }
}

function resetForm() {
  form.name = ''
  form.pattern = ''
  form.description = ''
  form.enabled = true
  editingId.value = null
  isBuiltin.value = false
}

function openCreate() {
  resetForm()
  showModal.value = true
}

function handleEdit(row) {
  resetForm()
  editingId.value = row.id
  isBuiltin.value = !!row.isBuiltIn
  form.name = row.name
  form.pattern = row.pattern
  form.description = row.description || ''
  form.enabled = !!row.enabled
  showModal.value = true
}

async function handleDuplicate(row) {
  resetForm()
  form.name = row.name + '（副本）'
  form.pattern = row.pattern
  form.description = row.description || ''
  form.enabled = !!row.enabled
  // 复制走 create 流程
  editingId.value = null
  isBuiltin.value = false
  showModal.value = true
}

async function handleSave() {
  if (!form.name.trim()) { message.warning('请输入名称'); return }
  if (!form.pattern.trim()) { message.warning('请输入匹配模式'); return }
  saving.value = true
  try {
    const payload = {
      name: form.name.trim(),
      pattern: form.pattern.trim(),
      description: form.description?.trim() || null,
      enabled: form.enabled
    }
    if (editingId.value == null) {
      await createHermesErrorPattern(payload)
      message.success('已创建')
    } else {
      await updateHermesErrorPattern(editingId.value, payload)
      message.success('已保存')
    }
    showModal.value = false
    await loadPatterns()
  } catch (e) {
    message.error(e.message || '保存失败')
  } finally {
    saving.value = false
  }
}

async function handleToggle(row, value) {
  row._toggling = true
  try {
    await toggleHermesErrorPattern(row.id)
    row.enabled = value
  } catch (e) {
    message.error(e.message || '切换失败')
  } finally {
    row._toggling = false
  }
}

async function handleDelete(row) {
  try {
    await deleteHermesErrorPattern(row.id)
    message.success('已删除')
    await loadPatterns()
  } catch (e) {
    message.error(e.message || '删除失败')
  }
}

async function handleReset() {
  try {
    await resetHermesErrorPatterns()
    message.success('已重置为默认')
    await loadPatterns()
  } catch (e) {
    message.error(e.message || '重置失败')
  }
}

onMounted(() => {
  loadPatterns()
})
</script>

<template>
  <div class="error-pattern-page">
    <div class="page-header">
      <div class="header-left">
        <h2 class="page-title">
          <n-icon size="22"><WarningOutline /></n-icon>
          错误模式管理
        </h2>
        <div class="page-subtitle">
          检测智能体响应中的 LLM 调用失败（HTTP 4xx / 限流 / 鉴权 / 配额），命中即按节点失败处理
        </div>
      </div>
      <div class="header-right">
        <n-button :loading="loading" @click="loadPatterns">
          <template #icon><n-icon><ReloadOutline /></n-icon></template>
          刷新
        </n-button>
        <n-popconfirm
          @positive-click="handleReset"
          positive-text="确定重置"
          negative-text="取消"
        >
          <template #trigger>
            <n-button>重置为默认</n-button>
          </template>
          将清空所有自定义模式，并把内置模式恢复为启用。确定继续？
        </n-popconfirm>
        <n-button type="primary" @click="openCreate">
          <template #icon><n-icon><AddOutline /></n-icon></template>
          新建模式
        </n-button>
      </div>
    </div>

    <div class="stats-row">
      <div class="stat-card">
        <span class="stat-label">总数</span>
        <span class="stat-value">{{ stats.total }}</span>
      </div>
      <div class="stat-card">
        <span class="stat-label">启用</span>
        <span class="stat-value enabled">{{ stats.enabled }}</span>
      </div>
      <div class="stat-card">
        <span class="stat-label">内置</span>
        <span class="stat-value">{{ stats.builtin }}</span>
      </div>
    </div>

    <div class="table-wrapper">
      <n-data-table
        class="pattern-table"
        :columns="columns"
        :data="patterns"
        :loading="loading"
        :bordered="false"
        :single-line="false"
        :striped="true"
        size="small"
        flex-height
        style="height: calc(100vh - var(--header-height) - 250px);"
      />
    </div>

    <n-modal
      v-model:show="showModal"
      preset="card"
      :title="editingId == null ? '新建错误模式' : (isBuiltin ? '编辑内置模式' : '编辑自定义模式')"
      :mask-closable="false"
      style="max-width: 520px"
      :bordered="false"
    >
      <n-form label-placement="top">
        <n-form-item label="名称">
          <n-input
            v-model:value="form.name"
            placeholder="如 LLM 429 限流"
            :disabled="isBuiltin"
          />
          <template #feedback>
            <span v-if="isBuiltin" style="color: var(--text-tertiary)">内置模式不可改名</span>
          </template>
        </n-form-item>
        <n-form-item label="匹配模式（子串、大小写不敏感）">
          <n-input
            v-model:value="form.pattern"
            placeholder="如 API call failed after"
            code
          />
        </n-form-item>
        <n-form-item label="说明">
          <n-input
            v-model:value="form.description"
            type="textarea"
            :rows="2"
            placeholder="可选：触发场景、影响范围"
          />
        </n-form-item>
        <n-form-item label="启用">
          <n-switch v-model:value="form.enabled" />
        </n-form-item>
      </n-form>
      <template #action>
        <n-button @click="showModal = false">取消</n-button>
        <n-button type="primary" :loading="saving" @click="handleSave">保存</n-button>
      </template>
    </n-modal>
  </div>
</template>

<style scoped>
.error-pattern-page {
  padding: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
  gap: 16px;
}

.page-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 4px 0;
}

.page-subtitle {
  font-size: 13px;
  color: var(--text-tertiary);
}

.header-right {
  display: flex;
  gap: 8px;
}

.stats-row {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.stat-card {
  flex: 1;
  padding: 12px 16px;
  background: var(--bg-card);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.stat-label {
  font-size: 12px;
  color: var(--text-tertiary);
}

.stat-value {
  font-size: 22px;
  font-weight: 600;
  color: var(--text-primary);
}

.stat-value.enabled {
  color: var(--color-accent);
}

.table-wrapper {
  background: var(--bg-card);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-md);
  padding: 8px;
}

/* ========== NDataTable 颜色覆盖（与模型管理页保持一致） ========== */
.pattern-table :deep(.n-data-table) {
  --n-td-color: #0f1e3c;
  --n-td-color-hover: rgba(37, 99, 235, 0.22);
  --n-th-color: rgba(37, 99, 235, 0.28);
  --n-th-text-color: var(--text-primary);
  --n-td-text-color: var(--text-primary);
  --n-border-color: rgba(56, 189, 248, 0.18);
  --n-td-color-striped: #0a1628;
}
.pattern-table :deep(.n-data-table-th) {
  background: rgba(37, 99, 235, 0.28) !important;
  color: var(--text-primary) !important;
  border-bottom: 1px solid rgba(56, 189, 248, 0.35) !important;
  font-size: 13px;
  font-weight: 600;
}
.pattern-table :deep(.n-data-table-td) {
  background: #0f1e3c !important;
  color: var(--text-primary) !important;
  border-bottom: 1px solid rgba(56, 189, 248, 0.1) !important;
}
.pattern-table :deep(.n-data-table-tr--striped .n-data-table-td) {
  background: #0a1628 !important;
}
.pattern-table :deep(.n-data-table-tr:hover .n-data-table-td) {
  background: rgba(37, 99, 235, 0.18) !important;
}
</style>
