<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { configApi } from '../../services/configApi'

const items = ref<string[]>([])
const newItem = ref('')
const editIndex = ref<number | null>(null)
const editText = ref('')
const loading = ref(false)
const saving = ref(false)
const error = ref('')
const success = ref('')

async function fetchItems() {
  loading.value = true
  error.value = ''
  try {
    const res = await configApi.getDomainKnowledge()
    items.value = res.data.items || []
  } catch (e: any) {
    error.value = 'Failed to load domain knowledge'
  } finally {
    loading.value = false
  }
}

async function save() {
  saving.value = true
  error.value = ''
  success.value = ''
  try {
    await configApi.updateDomainKnowledge(items.value)
    success.value = `Saved ${items.value.length} items`
    setTimeout(() => success.value = '', 3000)
  } catch (e: any) {
    error.value = 'Failed to save'
  } finally {
    saving.value = false
  }
}

function addItem() {
  const text = newItem.value.trim()
  if (!text) return
  items.value.push(text)
  newItem.value = ''
  save()
}

function removeItem(index: number) {
  items.value.splice(index, 1)
  save()
}

function startEdit(index: number) {
  editIndex.value = index
  editText.value = items.value[index]
}

function cancelEdit() {
  editIndex.value = null
  editText.value = ''
}

function saveEdit(index: number) {
  const text = editText.value.trim()
  if (!text) return
  items.value[index] = text
  editIndex.value = null
  editText.value = ''
  save()
}

function moveUp(index: number) {
  if (index <= 0) return
  const temp = items.value[index]
  items.value[index] = items.value[index - 1]
  items.value[index - 1] = temp
  save()
}

function moveDown(index: number) {
  if (index >= items.value.length - 1) return
  const temp = items.value[index]
  items.value[index] = items.value[index + 1]
  items.value[index + 1] = temp
  save()
}

onMounted(fetchItems)
</script>

<template>
  <div class="max-w-4xl">
    <div class="mb-4">
      <h3 class="text-lg font-semibold text-dark-100 mb-1">Domain Knowledge</h3>
      <p class="text-sm text-dark-400">
        Business-specific context included in every Claude API prompt.
        These help Claude understand your database structure, naming conventions, and data quirks.
      </p>
    </div>

    <!-- Status messages -->
    <div v-if="error" class="mb-3 px-3 py-2 bg-red-900/30 border border-red-600/40 rounded text-sm text-red-400">{{ error }}</div>
    <div v-if="success" class="mb-3 px-3 py-2 bg-green-900/30 border border-green-600/40 rounded text-sm text-green-400">{{ success }}</div>

    <!-- Loading -->
    <div v-if="loading" class="text-dark-400 text-sm py-8 text-center">Loading...</div>

    <!-- Items list -->
    <div v-else class="space-y-2 mb-4">
      <div v-if="items.length === 0" class="text-dark-500 text-sm py-6 text-center border border-dashed border-dark-600 rounded-lg">
        No domain knowledge items yet. Add one below.
      </div>

      <div
        v-for="(item, i) in items"
        :key="i"
        class="group flex items-start gap-2 bg-dark-800 border border-dark-700 rounded-lg p-3 hover:border-dark-500 transition-colors"
      >
        <!-- Edit mode -->
        <template v-if="editIndex === i">
          <textarea
            v-model="editText"
            rows="2"
            class="flex-1 bg-dark-900 border border-dark-600 rounded px-3 py-2 text-sm text-dark-200 resize-y focus:border-primary-500 focus:outline-none"
            @keydown.enter.ctrl="saveEdit(i)"
            @keydown.escape="cancelEdit"
          />
          <button @click="saveEdit(i)" class="px-2 py-1 text-xs text-green-400 hover:text-green-300">Save</button>
          <button @click="cancelEdit" class="px-2 py-1 text-xs text-dark-400 hover:text-dark-200">Cancel</button>
        </template>

        <!-- View mode -->
        <template v-else>
          <span class="text-dark-500 text-xs font-mono mt-0.5 select-none w-5 text-right shrink-0">{{ i + 1 }}</span>
          <p class="flex-1 text-sm text-dark-300 leading-relaxed">{{ item }}</p>
          <div class="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0">
            <button @click="moveUp(i)" :disabled="i === 0" class="p-1 text-dark-500 hover:text-dark-300 disabled:opacity-30" title="Move up">&#9650;</button>
            <button @click="moveDown(i)" :disabled="i === items.length - 1" class="p-1 text-dark-500 hover:text-dark-300 disabled:opacity-30" title="Move down">&#9660;</button>
            <button @click="startEdit(i)" class="p-1 text-dark-500 hover:text-primary-400" title="Edit">&#9998;</button>
            <button @click="removeItem(i)" class="p-1 text-dark-500 hover:text-red-400" title="Delete">&#10005;</button>
          </div>
        </template>
      </div>
    </div>

    <!-- Add new -->
    <div class="flex gap-2">
      <input
        v-model="newItem"
        type="text"
        placeholder="Add domain knowledge (e.g. 'The DUNS column for suppliers is KRAUS')"
        class="flex-1 bg-dark-800 border border-dark-600 rounded-lg px-3 py-2 text-sm text-dark-200 placeholder:text-dark-600 focus:border-primary-500 focus:outline-none"
        @keydown.enter="addItem"
      />
      <button
        @click="addItem"
        :disabled="!newItem.trim()"
        class="px-4 py-2 bg-primary-600 hover:bg-primary-500 disabled:bg-dark-700 disabled:text-dark-500 text-white text-sm rounded-lg font-medium transition-colors"
      >Add</button>
    </div>

    <!-- Item count -->
    <div class="mt-3 text-xs text-dark-500">
      {{ items.length }} item{{ items.length !== 1 ? 's' : '' }} &middot; Included in every Claude API system prompt
    </div>
  </div>
</template>
