<script setup lang="ts">
// src/renderer/src/components/CliView.vue
import { ref, computed, nextTick, watch } from 'vue'
import { useConnectionStore } from '@renderer/stores/connection'
import { redisCommands } from '@renderer/data/commands'

const connStore = useConnectionStore()

const input = ref('')
const history = ref<{ cmd: string; result: string; error?: boolean }[]>([])
const historyIndex = ref(-1)
const outputRef = ref<HTMLDivElement>()
const suggestionIndex = ref(-1)

const showSuggestions = computed(() => {
  return suggestions.value.length > 0 && !input.value.includes(' ')
})

const suggestions = computed(() => {
  const firstWord = input.value.split(/\s+/)[0]
  if (!firstWord) return []
  const prefix = firstWord.toUpperCase()
  return redisCommands
    .filter(cmd => cmd.name.startsWith(prefix))
    .slice(0, 8)
})

function selectSuggestion(cmd: string) {
  input.value = cmd + ' '
  suggestionIndex.value = -1
  inputRef.value?.focus()
}

async function execute() {
  if (!connStore.activeId || !input.value.trim()) return

  const cmd = input.value.trim()
  input.value = ''
  historyIndex.value = -1
  suggestionIndex.value = -1

  const parts = cmd.split(/\s+/)
  const command = parts[0].toUpperCase()
  const args = parts.slice(1)

  try {
    const result = await window.electronAPI.redis.execute(connStore.activeId, command, args)
    let formatted = ''

    if (result === null) {
      formatted = '(nil)'
    } else if (typeof result === 'number') {
      formatted = `(integer) ${result}`
    } else if (Array.isArray(result)) {
      if (result.length === 0) {
        formatted = '(empty array)'
      } else {
        formatted = result.map((item: any, i: number) => {
          if (item === null) return `${i + 1}) (nil)`
          if (typeof item === 'number') return `${i + 1}) (integer) ${item}`
          return `${i + 1}) "${item}"`
        }).join('\n')
      }
    } else if (typeof result === 'object') {
      formatted = JSON.stringify(result, null, 2)
    } else {
      formatted = String(result)
    }

    history.value.push({ cmd, result: formatted })
  } catch (err: any) {
    history.value.push({ cmd, result: `ERROR: ${err.message}`, error: true })
  }

  await nextTick()
  if (outputRef.value) {
    outputRef.value.scrollTop = outputRef.value.scrollHeight
  }
}

function onKeydown(e: KeyboardEvent) {
  if (showSuggestions.value) {
    if (e.key === 'ArrowDown') {
      e.preventDefault()
      suggestionIndex.value = Math.min(suggestionIndex.value + 1, suggestions.value.length - 1)
      return
    }
    if (e.key === 'ArrowUp') {
      e.preventDefault()
      suggestionIndex.value = Math.max(suggestionIndex.value - 1, -1)
      return
    }
    if (e.key === 'Enter' || e.key === 'Tab') {
      if (suggestionIndex.value >= 0 && suggestionIndex.value < suggestions.value.length) {
        e.preventDefault()
        selectSuggestion(suggestions.value[suggestionIndex.value].name)
        return
      }
    }
    if (e.key === 'Escape') {
      suggestionIndex.value = -1
      return
    }
  }

  if (e.key === 'Enter') {
    e.preventDefault()
    execute()
  } else if (e.key === 'ArrowUp') {
    e.preventDefault()
    if (historyIndex.value < history.value.length - 1) {
      historyIndex.value++
      input.value = history.value[history.value.length - 1 - historyIndex.value].cmd
    }
  } else if (e.key === 'ArrowDown') {
    e.preventDefault()
    if (historyIndex.value > 0) {
      historyIndex.value--
      input.value = history.value[history.value.length - 1 - historyIndex.value].cmd
    } else {
      historyIndex.value = -1
      input.value = ''
    }
  }
}

const inputRef = ref<HTMLInputElement>()

function categoryColor(category: string): string {
  switch (category) {
    case 'admin': return 'var(--color-red)'
    case 'read': return 'var(--color-green)'
    case 'write': return 'var(--color-yellow)'
    case 'server': return 'var(--color-blue)'
    case 'pubsub': return 'var(--color-purple)'
    default: return 'var(--text-primary)'
  }
}
</script>

<template>
  <div class="cli-view">
    <div class="cli-output" ref="outputRef">
      <div v-for="(item, index) in history" :key="index" class="cli-entry">
        <div class="cli-cmd">
          <span class="prompt">&gt;</span>
          <span>{{ item.cmd }}</span>
        </div>
        <pre class="cli-result" :class="{ error: item.error }">{{ item.result }}</pre>
      </div>
      <div v-if="history.length === 0" class="cli-welcome">
        Redis CLI - type commands below
      </div>
    </div>
    <div class="cli-input-bar">
      <span class="prompt">&gt;</span>
      <div class="cli-input-wrapper">
        <input
          ref="inputRef"
          v-model="input"
          class="cli-input"
          placeholder="Enter Redis command..."
          @keydown="onKeydown"
          autofocus
        />
        <div v-if="showSuggestions" class="cli-suggestions">
          <div
            v-for="(cmd, index) in suggestions"
            :key="cmd.name"
            class="cli-suggestion-item"
            :class="{ active: index === suggestionIndex }"
            @click="selectSuggestion(cmd.name)"
            @mouseenter="suggestionIndex = index"
          >
            <span class="suggestion-name" :style="{ color: categoryColor(cmd.category) }">{{ cmd.name }}</span>
            <span class="suggestion-syntax">{{ cmd.syntax }}</span>
            <span class="suggestion-desc">{{ cmd.description }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.cli-view {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: var(--bg-primary);
}

.cli-output {
  flex: 1;
  overflow-y: auto;
  padding: 12px;
  font-family: 'Cascadia Code', 'Fira Code', monospace;
  font-size: 13px;
}

.cli-welcome {
  color: var(--text-muted);
  padding: 20px 0;
}

.cli-entry {
  margin-bottom: 12px;
}

.cli-cmd {
  color: var(--accent-light);
}

.prompt {
  color: var(--color-green);
  margin-right: 6px;
}

.cli-result {
  color: var(--text-secondary);
  margin: 4px 0 0 18px;
  white-space: pre-wrap;
  word-break: break-all;
  font-size: 12px;
}

.cli-result.error {
  color: var(--color-red);
}

.cli-input-bar {
  padding: 10px 12px;
  border-top: 1px solid var(--border-color);
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

.cli-input-wrapper {
  flex: 1;
  position: relative;
  margin-left: 6px;
}

.cli-input {
  width: 100%;
  background: transparent;
  border: none;
  outline: none;
  color: var(--text-primary);
  font-family: 'Cascadia Code', 'Fira Code', monospace;
  font-size: 13px;
}

.cli-input::placeholder {
  color: var(--text-muted);
}

.cli-suggestions {
  position: absolute;
  bottom: 100%;
  left: 0;
  right: 0;
  margin-bottom: 4px;
  background: var(--bg-secondary);
  border: 1px solid var(--border-color);
  border-radius: 6px;
  max-height: 320px;
  overflow-y: auto;
  z-index: 100;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.cli-suggestion-item {
  display: flex;
  flex-direction: column;
  padding: 6px 10px;
  cursor: pointer;
  border-bottom: 1px solid var(--border-color);
  gap: 2px;
}

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

.cli-suggestion-item.active,
.cli-suggestion-item:hover {
  background: var(--bg-hover);
}

.suggestion-name {
  font-weight: 600;
  font-size: 13px;
  font-family: 'Cascadia Code', 'Fira Code', monospace;
}

.suggestion-syntax {
  font-size: 11px;
  color: var(--text-muted);
  font-family: 'Cascadia Code', 'Fira Code', monospace;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.suggestion-desc {
  font-size: 11px;
  color: var(--text-secondary);
}
</style>
