<template>
  <div class="space-y-6">
    <div class="flex items-center gap-4">
      <GlassButton @click="$router.back()" class="!px-3 !py-2">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
        </svg>
      </GlassButton>
      <h1 class="text-3xl font-bold text-white">Server Detail</h1>
    </div>

    <!-- Loading State -->
    <div v-if="loading" class="text-center py-8 text-white/50">Loading server information...</div>

    <!-- Error State -->
    <div v-if="error" class="p-4 bg-red-500/20 border border-red-500/50 rounded-lg text-red-400">
      {{ error }}
    </div>

    <!-- Server Information -->
    <GlassCard v-if="server" class="p-6">
      <h2 class="text-xl font-semibold text-cyan-400 mb-4">Server Information</h2>
      <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <p class="text-white/50 text-sm">Server Name</p>
          <p class="text-white text-lg">{{ server.name }}</p>
        </div>
        <div>
          <p class="text-white/50 text-sm">Mode</p>
          <span
            class="inline-block px-3 py-1 rounded-full text-sm"
            :class="server.mode === 'forward' ? 'bg-cyan-500/20 text-cyan-400' : 'bg-purple-500/20 text-purple-400'"
          >
            {{ server.mode }}
          </span>
        </div>
        <div>
          <p class="text-white/50 text-sm">Public Key</p>
          <p class="text-white font-mono text-sm break-all">{{ server.publicKey }}</p>
        </div>
        <div>
          <p class="text-white/50 text-sm">Endpoint</p>
          <p class="text-white font-mono text-sm">{{ server.endpoint || 'Not set' }}</p>
        </div>
      </div>
    </GlassCard>

    <!-- Peer Table -->
    <PeerTable v-if="server" :server-id="$route.params.id as string" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import GlassCard from '../components/glass/GlassCard.vue'
import GlassButton from '../components/glass/GlassButton.vue'
import PeerTable from '../components/PeerTable.vue'

interface Server {
  id: string
  name: string
  mode: 'forward' | 'standalone'
  publicKey: string
  endpoint?: string
}

const server = ref<Server | null>(null)
const loading = ref(true)
const error = ref<string | null>(null)

onMounted(async () => {
  try {
    const serverId = (window as any).$route?.params?.id || '1'
    const response = await fetch(`/api/servers/${serverId}`)
    if (!response.ok) throw new Error('Failed to fetch server details')
    server.value = await response.json()
  } catch (err) {
    error.value = err instanceof Error ? err.message : 'An error occurred'
    console.error('Failed to load server:', err)
  } finally {
    loading.value = false
  }
})
</script>
