<script setup lang="ts">
const props = defineProps({
  tool: { type: Object as PropType<any>, default: null },
})

const emit = defineEmits(["close"])

const { $toast } = useNuxtApp()
const isEdit = computed(() => !!props.tool)

interface ToolTypeMeta {
  type: string
  defaultConfig: Record<string, unknown>
  inputSchema: Record<string, unknown>
}

const { data: typesData } = await useHttpFetch("/api/agent-tools/types")
const typeMetaList = computed<ToolTypeMeta[]>(() => (typesData.value as any) ?? [])

const typeItems = computed(() =>
  typeMetaList.value.map((m) => ({ label: m.type, value: m.type })),
)

function getMeta(type: string): ToolTypeMeta | undefined {
  return typeMetaList.value.find((m) => m.type === type)
}

const form = reactive({
  name: props.tool?.name ?? "",
  slug: props.tool?.slug ?? "",
  description: props.tool?.description ?? "",
  type: (props.tool?.type ?? "fetch") as string,
  config: props.tool?.config ?? "",
  inputSchema: "",
  enabled: props.tool ? props.tool.enabled === 1 : true,
  needsApproval: props.tool ? props.tool.needsApproval === 1 : false,
  adminOnly: props.tool ? props.tool.adminOnly === 1 : false,
  sortOrder: props.tool?.sortOrder ?? 0,
})

function initForm() {
  const meta = getMeta(form.type)
  if (!props.tool) {
    form.config = meta ? JSON.stringify(meta.defaultConfig, null, 2) : ""
  } else if (typeof props.tool.config === "string") {
    try {
      form.config = JSON.stringify(JSON.parse(props.tool.config), null, 2)
    } catch {
      form.config = props.tool.config
    }
  } else {
    form.config = JSON.stringify(props.tool.config ?? meta?.defaultConfig ?? {}, null, 2)
  }
  form.inputSchema = meta ? JSON.stringify(meta.inputSchema, null, 2) : ""
}

initForm()

watch(
  () => form.type,
  (newType) => {
    const meta = getMeta(newType)
    if (meta) {
      if (!isEdit.value) {
        form.config = JSON.stringify(meta.defaultConfig, null, 2)
      }
      form.inputSchema = JSON.stringify(meta.inputSchema, null, 2)
    }
  },
)

const saving = ref(false)
const error = ref("")

async function save() {
  saving.value = true
  error.value = ""

  let parsedConfig: any
  try {
    parsedConfig = JSON.parse(form.config)
  } catch {
    error.value = "config 不是合法 JSON"
    saving.value = false
    return
  }

  const body = {
    name: form.name,
    slug: form.slug,
    description: form.description,
    type: form.type,
    config: parsedConfig,
    enabled: form.enabled ? 1 : 0,
    needsApproval: form.needsApproval ? 1 : 0,
    adminOnly: form.adminOnly ? 1 : 0,
    sortOrder: Number(form.sortOrder) || 0,
  }

  try {
    if (isEdit.value) {
      await $fetch(`/api/agent-tools/${props.tool.id}`, {
        method: "PUT",
        body,
      })
      $toast.success("更新成功")
    } else {
      await $fetch("/api/agent-tools", {
        method: "POST",
        body,
      })
      $toast.success("创建成功")
    }
    emit("close")
  } catch (err: any) {
    error.value = err?.data?.message ?? err?.message ?? "保存失败"
  } finally {
    saving.value = false
  }
}

function onOverlayClick(e: MouseEvent) {
  if ((e.target as HTMLElement).dataset.overlay === "true") {
    emit("close")
  }
}
</script>

<template>
  <div data-overlay="true" class="modal-overlay" @click="onOverlayClick">
    <div class="modal-container">
      <div class="modal-header">
        <h2 class="modal-title">{{ isEdit ? '编辑' : '创建' }}工具</h2>
        <button class="modal-close-btn" @click="emit('close')">
          <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
          </svg>
        </button>
      </div>

      <div class="modal-body">
        <div v-if="error" class="error-alert">{{ error }}</div>

        <div class="form-group">
          <label class="form-label">名称 *</label>
          <input v-model="form.name" type="text" placeholder="工具名称" class="form-input" />
        </div>

        <div class="form-group">
          <label class="form-label">Slug *</label>
          <input v-model="form.slug" type="text" placeholder="如 fetch_web_page" class="form-input form-input-mono" />
          <div class="form-hint">LLM 调用时使用的唯一标识，小写字母+下划线</div>
        </div>

        <div class="form-group">
          <label class="form-label">描述 *</label>
          <textarea v-model="form.description" rows="2" placeholder="告诉 LLM 这个工具能做什么" class="form-textarea"></textarea>
        </div>

        <div class="form-group">
          <label class="form-label">类型 *</label>
          <select v-model="form.type" class="form-select">
            <option v-for="item in typeItems" :key="item.value" :value="item.value">{{ item.label }}</option>
          </select>
        </div>

        <div class="form-group">
          <label class="form-label">Input Schema（只读）</label>
          <textarea :value="form.inputSchema" rows="6" readonly class="form-textarea form-input-mono form-input-readonly"></textarea>
          <div class="form-hint">由工具类型决定，切换类型时自动更新</div>
        </div>

        <div class="form-group">
          <label class="form-label">Config (JSON)</label>
          <textarea v-model="form.config" rows="8" class="form-textarea form-input-mono"></textarea>
          <div class="form-hint">工具执行器的差异化配置</div>
        </div>

        <div class="form-row">
          <div class="form-group form-group-sm">
            <label class="form-label">排序</label>
            <input v-model.number="form.sortOrder" type="number" min="0" class="form-input" />
          </div>
          <div class="form-group form-group-grow">
            <label class="checkbox-label">
              <input v-model="form.enabled" type="checkbox" class="form-checkbox" />
              <span>启用</span>
            </label>
          </div>
          <div class="form-group form-group-grow">
            <label class="checkbox-label">
              <input v-model="form.needsApproval" type="checkbox" class="form-checkbox" />
              <span>需要审批</span>
            </label>
          </div>
          <div class="form-group form-group-grow">
            <label class="checkbox-label">
              <input v-model="form.adminOnly" type="checkbox" class="form-checkbox" />
              <span>仅管理员可用</span>
            </label>
          </div>
        </div>
      </div>

      <div class="modal-footer">
        <button class="btn-secondary" @click="emit('close')">取消</button>
        <button :disabled="saving" class="btn-primary" @click="save">
          {{ saving ? '保存中...' : (isEdit ? '更新' : '创建') }}
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.modal-overlay {
  position: fixed;
  inset: 0;
  z-index: 50;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding-top: 8vh;
  background: rgba(20, 20, 19, 0.4);
}

.modal-container {
  background: var(--color-canvas);
  border-radius: 12px;
  box-shadow: 0 20px 40px rgba(20, 20, 19, 0.2);
  width: 100%;
  max-width: 600px;
  max-height: 84vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px;
  border-bottom: 1px solid var(--color-hairline);
}

.modal-title {
  font-size: 18px;
  font-weight: 500;
  color: var(--color-ink);
  margin: 0;
}

.modal-close-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border: none;
  background: transparent;
  border-radius: 6px;
  color: var(--color-muted);
  cursor: pointer;
  transition: all 0.15s ease;
}

.modal-close-btn:hover {
  background: var(--color-surface-soft);
  color: var(--color-ink);
}

.modal-body {
  padding: 24px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding: 16px 24px;
  border-top: 1px solid var(--color-hairline);
  background: var(--color-surface-soft);
  border-radius: 0 0 12px 12px;
}

.error-alert {
  padding: 12px 16px;
  background: rgba(198, 69, 69, 0.08);
  color: var(--color-error);
  border-radius: 8px;
  font-size: 14px;
}

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

.form-group-grow {
  flex: 1;
}

.form-group-sm {
  width: 120px;
}

.form-label {
  font-size: 14px;
  font-weight: 500;
  color: var(--color-body-strong);
}

.form-hint {
  font-size: 12px;
  color: var(--color-muted);
}

.form-input,
.form-select,
.form-textarea {
  width: 100%;
  padding: 10px 14px;
  font-size: 14px;
  color: var(--color-ink);
  background: var(--color-canvas);
  border: 1px solid var(--color-hairline);
  border-radius: 8px;
  transition: all 0.15s ease;
}

.form-input:focus,
.form-select:focus,
.form-textarea:focus {
  outline: none;
  border-color: var(--color-primary);
  box-shadow: 0 0 0 3px rgba(204, 120, 92, 0.15);
}

.form-input-mono {
  font-family: 'JetBrains Mono', monospace;
  font-size: 13px;
}

.form-input-readonly {
  background: var(--color-surface-soft);
  color: var(--color-muted);
  cursor: default;
}

.form-textarea {
  resize: vertical;
  min-height: 60px;
}

.form-row {
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: var(--color-body);
  cursor: pointer;
}

.form-checkbox {
  width: 16px;
  height: 16px;
  accent-color: var(--color-primary);
  cursor: pointer;
}

.btn-secondary {
  padding: 10px 16px;
  font-size: 14px;
  font-weight: 500;
  color: var(--color-body-strong);
  background: var(--color-canvas);
  border: 1px solid var(--color-hairline);
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.15s ease;
}

.btn-secondary:hover {
  background: var(--color-surface-soft);
}

.btn-primary {
  padding: 10px 16px;
  font-size: 14px;
  font-weight: 500;
  color: var(--color-on-primary);
  background: var(--color-primary);
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: background 0.15s ease;
}

.btn-primary:hover {
  background: var(--color-primary-active);
}

.btn-primary:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}
</style>
