<script setup lang="ts">
import { ref, nextTick, onMounted } from 'vue'
import { useServerStore } from '@/stores/server'
import { Send, Terminal, Trash2 } from 'lucide-vue-next'

const server = useServerStore()

interface ConsoleLine {
  timestamp: string
  text: string
  type: 'info' | 'warning' | 'error' | 'command' | 'system'
}

const lines = ref<ConsoleLine[]>([])
const commandInput = ref('')
const consoleEl = ref<HTMLElement | null>(null)
const sending = ref(false)

function now(): string {
  return new Date().toLocaleTimeString('en-US', { hour12: false })
}

function addLine(text: string, type: ConsoleLine['type'] = 'info') {
  lines.value.push({ timestamp: now(), text, type })
  scrollToBottom()
}

async function scrollToBottom() {
  await nextTick()
  if (consoleEl.value) {
    consoleEl.value.scrollTop = consoleEl.value.scrollHeight
  }
}

async function handleSend() {
  const cmd = commandInput.value.trim()
  if (!cmd || sending.value) return

  addLine(`> ${cmd}`, 'command')
  commandInput.value = ''
  sending.value = true

  try {
    const result = await server.sendCommand(cmd) as { output?: string }
    if (result?.output) {
      addLine(result.output, 'info')
    } else {
      addLine('Command sent.', 'system')
    }
  } catch {
    addLine('Failed to send command. Is the server connected?', 'error')
  } finally {
    sending.value = false
  }
}

function clearConsole() {
  lines.value = []
}

function lineColor(type: ConsoleLine['type']): string {
  switch (type) {
    case 'command': return 'text-oxide-400'
    case 'warning': return 'text-yellow-400'
    case 'error': return 'text-red-400'
    case 'system': return 'text-neutral-500'
    default: return 'text-neutral-300'
  }
}

onMounted(() => {
  addLine('Corrosion Console initialized.', 'system')
  addLine('Type a command and press Enter to send it to the server.', 'system')
  if (server.connection?.connection_status !== 'connected') {
    addLine('WARNING: Server is not connected. Commands will fail.', 'warning')
  }
})
</script>

<template>
  <div class="p-6 h-full flex flex-col">
    <!-- Header -->
    <div class="flex items-center justify-between mb-4">
      <div class="flex items-center gap-3">
        <Terminal class="w-5 h-5 text-oxide-500" />
        <h1 class="text-2xl font-bold text-neutral-100">Server Console</h1>
      </div>
      <div class="flex items-center gap-3">
        <div class="flex items-center gap-2 text-sm">
          <span
            class="h-2 w-2 rounded-full"
            :class="server.connection?.connection_status === 'connected' ? 'bg-green-500' : 'bg-red-500'"
          />
          <span class="text-neutral-400">
            {{ server.connection?.connection_status === 'connected' ? 'Connected' : 'Disconnected' }}
          </span>
        </div>
        <button
          @click="clearConsole"
          class="flex items-center gap-1.5 px-3 py-1.5 text-sm text-neutral-400 hover:text-neutral-200 bg-neutral-800 hover:bg-neutral-700 rounded-lg transition-colors"
        >
          <Trash2 class="w-3.5 h-3.5" />
          Clear
        </button>
      </div>
    </div>

    <!-- Console output -->
    <div
      ref="consoleEl"
      class="flex-1 bg-black/80 border border-neutral-800 rounded-t-lg p-4 overflow-y-auto font-mono text-sm leading-relaxed min-h-0"
    >
      <div v-if="lines.length === 0" class="text-neutral-600 italic">
        No output yet. Send a command to get started.
      </div>
      <div
        v-for="(line, i) in lines"
        :key="i"
        class="flex gap-3"
      >
        <span class="text-neutral-600 shrink-0 select-none">{{ line.timestamp }}</span>
        <span :class="lineColor(line.type)" class="whitespace-pre-wrap break-all">{{ line.text }}</span>
      </div>
    </div>

    <!-- Command input -->
    <div class="flex bg-neutral-900 border border-t-0 border-neutral-800 rounded-b-lg overflow-hidden">
      <span class="flex items-center px-3 text-oxide-500 font-mono text-sm select-none">$</span>
      <input
        v-model="commandInput"
        @keydown.enter="handleSend"
        type="text"
        placeholder="say Hello everyone..."
        :disabled="sending"
        class="flex-1 bg-transparent py-3 text-neutral-100 placeholder-neutral-600 font-mono text-sm focus:outline-none disabled:opacity-50"
      />
      <button
        @click="handleSend"
        :disabled="!commandInput.trim() || sending"
        class="flex items-center gap-2 px-4 text-sm font-medium text-oxide-400 hover:text-oxide-300 disabled:opacity-30 disabled:cursor-not-allowed transition-colors"
      >
        <Send class="w-4 h-4" />
        Send
      </button>
    </div>
  </div>
</template>
