<script setup lang="ts">
import { NButton, NInputNumber, NSpin, NSwitch } from 'naive-ui'
import { reactive, ref, watch } from 'vue'

import { getAiSettings, listAiBlacklist, removeAiBlacklist, updateAiSettings } from '@/api/aigateway'
import BlacklistAddModal from '@/components/settings/BlacklistAddModal.vue'
import { useAsync } from '@/composables/useAsync'
import { fmtTime } from '@/composables/useFormat'
import { useToast } from '@/composables/useToast'
import type { AiSettings } from '@/types/api'

const toast = useToast()

const settings = useAsync(getAiSettings)
const blacklist = useAsync(listAiBlacklist)

/** 本地表单镜像:开关即时提交,数字输入失焦/回车提交 */
const form = reactive<AiSettings>({
  filterDeprecated: false,
  streamGuardEnabled: true,
  streamGuardKB: 60,
  grokWebSearch: true,
  grokXSearch: true,
})

watch(
  () => settings.data.value,
  (v) => {
    if (v) Object.assign(form, v)
  },
  { immediate: true },
)

const saving = ref(false)

/** 全量 PUT;失败回滚到服务端最新值 */
async function save() {
  saving.value = true
  try {
    Object.assign(form, await updateAiSettings({ ...form }))
    toast.success('已保存,即时生效')
  } catch (e) {
    toast.error(e instanceof Error ? e.message : '保存失败')
    void settings.run({ silent: true })
  } finally {
    saving.value = false
  }
}

function setField<K extends keyof AiSettings>(key: K, value: AiSettings[K]) {
  form[key] = value
  void save()
}

/** 阈值失焦/回车提交;NInputNumber 已按 min/max 收敛 */
function commitGuardKB(v: number | null) {
  if (v == null || v === form.streamGuardKB) return
  setField('streamGuardKB', v)
}

const removing = ref(0)
async function doRemove(id: number, name: string) {
  removing.value = id
  try {
    await removeAiBlacklist(id)
    toast.success(`已移出黑名单:${name},重新同步渠道后恢复`)
    void blacklist.run({ silent: true })
  } catch (e) {
    toast.error(e instanceof Error ? e.message : '移出失败')
  } finally {
    removing.value = 0
  }
}

const showAdd = ref(false)
function onBlacklistChanged() {
  void blacklist.run({ silent: true })
}
</script>

<template>
  <div v-if="settings.loading.value && !settings.data.value" class="panel flex max-w-[880px] items-center justify-center py-20">
    <NSpin size="small" />
  </div>
  <div v-else class="flex max-w-[880px] flex-col gap-4">
    <!-- 流式保险丝 -->
    <div class="panel">
      <div class="border-b border-line-soft px-4.5 py-3.5">
        <div class="text-sm font-semibold">流式保险丝</div>
      </div>
      <div class="px-4.5">
        <div class="flex items-center justify-between gap-3 py-3.5">
          <div class="min-w-0">
            <div class="text-[13px] font-medium">instructions + tools 阈值</div>
            <div class="mt-0.5 text-xs text-ink-3">
              系统提示与工具定义合计超过阈值的流式请求,预防性改走非流式上游并合成
              SSE:丢增量输出,保会话不中断
            </div>
          </div>
          <div class="flex flex-none items-center gap-3">
            <NInputNumber
              :value="form.streamGuardKB"
              :min="1"
              :max="1024"
              :show-button="false"
              :disabled="!form.streamGuardEnabled"
              size="small"
              class="w-24"
              :update-value-on-input="false"
              @update:value="commitGuardKB"
            >
              <template #suffix><span class="text-xs text-ink-3">KB</span></template>
            </NInputNumber>
            <NSwitch
              :value="form.streamGuardEnabled"
              size="small"
              :loading="saving"
              @update:value="(v: boolean) => setField('streamGuardEnabled', v)"
            />
          </div>
        </div>
      </div>
      <div class="border-t border-line-soft bg-wash px-4.5 py-2.5 text-xs leading-relaxed text-ink-3">
        修改即时生效,无需重启 · 仅作用于 Responses 直通面;Chat / Messages 已有断流自动重做兜底
      </div>
    </div>

    <!-- grok 服务端搜索工具 -->
    <div class="panel">
      <div class="border-b border-line-soft px-4.5 py-3.5">
        <div class="text-sm font-semibold">grok 服务端搜索工具</div>
        <div class="mt-0.5 text-xs text-ink-3">
          仅对 <span class="mono">xai.</span> 前缀模型的对话请求生效;请求 tools
          已包含同名工具时保持原样,不覆盖参数
        </div>
      </div>
      <div class="px-4.5">
        <div class="flex items-center justify-between gap-3 border-b border-line-soft py-3">
          <div class="text-[13px] font-medium">默认开启 web_search</div>
          <NSwitch
            :value="form.grokWebSearch"
            size="small"
            :loading="saving"
            @update:value="(v: boolean) => setField('grokWebSearch', v)"
          />
        </div>
        <div class="flex items-center justify-between gap-3 py-3">
          <div class="text-[13px] font-medium">默认开启 x_search</div>
          <NSwitch
            :value="form.grokXSearch"
            size="small"
            :loading="saving"
            @update:value="(v: boolean) => setField('grokXSearch', v)"
          />
        </div>
      </div>
    </div>

    <!-- 模型治理(自 AI 网关页迁入) -->
    <div class="panel">
      <div class="border-b border-line-soft px-4.5 py-3.5">
        <div class="text-sm font-semibold">模型治理</div>
      </div>
      <div class="px-4.5 pb-4">
        <div class="flex items-center justify-between gap-3 border-b border-line-soft py-3.5">
          <div class="min-w-0">
            <div class="text-[13px] font-medium">过滤弃用模型</div>
            <div class="mt-0.5 text-xs text-ink-3">
              开启后,已宣布弃用(即使未退役)的模型从模型列表与路由中排除;关闭恢复展示
            </div>
          </div>
          <NSwitch
            :value="form.filterDeprecated"
            size="small"
            :loading="saving"
            @update:value="(v: boolean) => setField('filterDeprecated', v)"
          />
        </div>
        <div class="flex items-center justify-between gap-3 pt-3.5 pb-1">
          <div class="min-w-0">
            <div class="text-[13px] font-medium">模型黑名单</div>
            <div class="mt-0.5 text-xs text-ink-3">
              命中的模型从模型列表与路由排除,重新同步渠道后移出才恢复
            </div>
          </div>
          <NButton size="tiny" quaternary type="primary" @click="showAdd = true">＋ 添加模型</NButton>
        </div>
        <table class="mt-1.5 w-full border-collapse">
          <thead>
            <tr class="border-y border-line-soft text-left text-xs font-medium text-ink-3">
              <th class="w-[52%] px-3 py-2">模型</th>
              <th class="px-3 py-2">加入时间</th>
              <th class="w-22 px-3 py-2">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr
              v-for="b in blacklist.data.value ?? []"
              :key="b.id"
              class="border-b border-line-soft last:border-b-0"
            >
              <td class="px-3 py-2"><span class="mono text-[13px]">{{ b.name }}</span></td>
              <td class="px-3 py-2 text-xs text-ink-3">{{ fmtTime(b.createdAt) }}</td>
              <td class="px-3 py-2">
                <NButton
                  size="tiny"
                  quaternary
                  type="error"
                  :loading="removing === b.id"
                  @click="doRemove(b.id, b.name)"
                >
                  移出
                </NButton>
              </td>
            </tr>
            <tr v-if="!(blacklist.data.value ?? []).length">
              <td colspan="3" class="px-3 py-6 text-center text-xs text-ink-3">
                黑名单为空;点右上「＋ 添加模型」从聚合模型目录选择
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <BlacklistAddModal
      v-model:show="showAdd"
      :blacklisted="(blacklist.data.value ?? []).map((b) => b.name)"
      @changed="onBlacklistChanged"
    />
  </div>
</template>
