<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useApi } from '@/composables/useApi'
import { Server, Search } from 'lucide-vue-next'

const api = useApi()

interface ServerEntry {
  id: string
  server_name: string
  owner_email: string
  connection_type: 'plugin' | 'companion' | 'amp' | 'pterodactyl' | 'bare_metal'
  status: 'connected' | 'degraded' | 'offline'
  server_ip: string
  game_port: number
  last_heartbeat: string
}

interface ServerListResponse {
  servers: ServerEntry[]
}

const servers = ref<ServerEntry[]>([])
const isLoading = ref(false)
const statusFilter = ref('all')
const searchQuery = ref('')

const statusOptions = [
  { value: 'all', label: 'All' },
  { value: 'connected', label: 'Connected' },
  { value: 'degraded', label: 'Degraded' },
  { value: 'offline', label: 'Offline' },
]

const connectionBadgeClass: Record<string, string> = {
  plugin: 'bg-blue-500/10 text-blue-400',
  companion: 'bg-purple-500/10 text-purple-400',
  amp: 'bg-cyan-500/10 text-cyan-400',
  pterodactyl: 'bg-green-500/10 text-green-400',
  bare_metal: 'bg-orange-500/10 text-orange-400',
}

const statusDotClass: Record<string, string> = {
  connected: 'bg-green-500',
  degraded: 'bg-yellow-500',
  offline: 'bg-red-500',
}

const statusTextClass: Record<string, string> = {
  connected: 'text-green-400',
  degraded: 'text-yellow-400',
  offline: 'text-red-400',
}

const filteredServers = computed(() => {
  let result = servers.value

  if (statusFilter.value !== 'all') {
    result = result.filter(s => s.status === statusFilter.value)
  }

  if (searchQuery.value.trim()) {
    const q = searchQuery.value.toLowerCase()
    result = result.filter(s =>
      s.server_name.toLowerCase().includes(q) ||
      s.owner_email.toLowerCase().includes(q) ||
      s.server_ip.includes(q)
    )
  }

  return result
})

function relativeTime(iso: string): string {
  const diff = Date.now() - new Date(iso).getTime()
  const seconds = Math.floor(diff / 1000)
  const minutes = Math.floor(seconds / 60)
  const hours = Math.floor(minutes / 60)
  const days = Math.floor(hours / 24)

  if (seconds < 60) return 'Just now'
  if (minutes < 60) return `${minutes} min ago`
  if (hours < 24) return `${hours} hour${hours !== 1 ? 's' : ''} ago`
  return `${days} day${days !== 1 ? 's' : ''} ago`
}

async function fetchServers() {
  isLoading.value = true
  try {
    const params = new URLSearchParams()
    if (statusFilter.value !== 'all') params.set('status', statusFilter.value)

    const query = params.toString()
    const path = query ? `/admin/servers?${query}` : '/admin/servers'
    const data = await api.get<ServerListResponse>(path)
    servers.value = data.servers
  } catch {
    // API not wired yet
  } finally {
    isLoading.value = false
  }
}

watch(statusFilter, () => {
  fetchServers()
})

onMounted(() => {
  fetchServers()
})
</script>

<template>
  <div class="p-6 space-y-6 bg-neutral-950 min-h-screen">
    <!-- Header -->
    <div class="flex items-center gap-3">
      <Server class="w-5 h-5 text-oxide-500" />
      <div>
        <h1 class="text-2xl font-bold text-neutral-100">Server Overview</h1>
        <p class="text-sm text-neutral-400 mt-0.5">
          {{ filteredServers.length }} server{{ filteredServers.length !== 1 ? 's' : '' }}
          <template v-if="statusFilter !== 'all'"> ({{ statusFilter }})</template>
        </p>
      </div>
    </div>

    <!-- Filters -->
    <div class="flex items-center gap-4">
      <div class="relative flex-1 max-w-sm">
        <Search class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-neutral-500" />
        <input
          v-model="searchQuery"
          type="text"
          placeholder="Search by server name, email, or IP..."
          class="w-full pl-10 pr-3 py-2 bg-neutral-800 border border-neutral-700 rounded-lg text-sm text-neutral-100 placeholder-neutral-500 focus:outline-none focus:ring-2 focus:ring-oxide-500/50 focus:border-oxide-500 transition-colors"
        />
      </div>
      <select
        v-model="statusFilter"
        class="px-3 py-2 bg-neutral-800 border border-neutral-700 rounded-lg text-sm text-neutral-100 focus:outline-none focus:ring-2 focus:ring-oxide-500/50 focus:border-oxide-500 transition-colors"
      >
        <option v-for="opt in statusOptions" :key="opt.value" :value="opt.value">
          {{ opt.label }}
        </option>
      </select>
    </div>

    <!-- Table -->
    <div class="bg-neutral-900 border border-neutral-800 rounded-lg overflow-hidden">
      <table class="w-full">
        <thead>
          <tr class="border-b border-neutral-800 text-left">
            <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Server Name</th>
            <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Owner Email</th>
            <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Connection Type</th>
            <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Status</th>
            <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Server IP</th>
            <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Game Port</th>
            <th class="px-4 py-3 text-xs font-medium text-neutral-500 uppercase tracking-wider">Last Heartbeat</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-neutral-800">
          <tr v-if="filteredServers.length === 0 && !isLoading">
            <td colspan="7" class="px-4 py-12 text-center text-neutral-500 text-sm">
              <template v-if="searchQuery">No servers matching "{{ searchQuery }}"</template>
              <template v-else-if="statusFilter !== 'all'">No {{ statusFilter }} servers found.</template>
              <template v-else>No servers found.</template>
            </td>
          </tr>
          <tr v-if="isLoading">
            <td colspan="7" class="px-4 py-12 text-center text-neutral-500 text-sm">Loading servers...</td>
          </tr>
          <tr
            v-for="srv in filteredServers"
            :key="srv.id"
            class="hover:bg-neutral-800/50 transition-colors"
          >
            <td class="px-4 py-3 text-sm font-medium text-neutral-100">{{ srv.server_name }}</td>
            <td class="px-4 py-3 text-sm text-neutral-400">{{ srv.owner_email }}</td>
            <td class="px-4 py-3">
              <span
                class="inline-flex text-xs font-medium px-2 py-0.5 rounded-full capitalize"
                :class="connectionBadgeClass[srv.connection_type] || 'bg-neutral-700/50 text-neutral-400'"
              >
                {{ srv.connection_type.replace('_', ' ') }}
              </span>
            </td>
            <td class="px-4 py-3">
              <div class="flex items-center gap-2">
                <span class="h-2 w-2 rounded-full" :class="statusDotClass[srv.status] || 'bg-neutral-500'" />
                <span class="text-sm capitalize" :class="statusTextClass[srv.status] || 'text-neutral-400'">
                  {{ srv.status }}
                </span>
              </div>
            </td>
            <td class="px-4 py-3 text-sm text-neutral-400 font-mono">{{ srv.server_ip }}</td>
            <td class="px-4 py-3 text-sm text-neutral-400 font-mono">{{ srv.game_port }}</td>
            <td class="px-4 py-3 text-sm text-neutral-400">{{ relativeTime(srv.last_heartbeat) }}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>
