<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useApi } from '@/composables/useApi'
import Panel from '@/components/ds/data/Panel.vue'
import Badge from '@/components/ds/core/Badge.vue'
import StatusDot from '@/components/ds/core/StatusDot.vue'
import Icon from '@/components/ds/core/Icon.vue'
import Input from '@/components/ds/forms/Input.vue'
import Select from '@/components/ds/forms/Select.vue'
import EmptyState from '@/components/ds/feedback/EmptyState.vue'

const api = useApi()

interface ServerEntry {
  license_id: string
  server_name: string | null
  owner_email: string
  connection_type: string
  connection_status: 'connected' | 'degraded' | 'offline'
  server_ip: string | null
  game_port: number | null
  plugin_last_seen: string | null
  companion_last_seen: string | null
}

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 connTypeTone: Record<string, 'info' | 'accent' | 'neutral' | 'online' | 'warn'> = {
  plugin: 'info',
  companion: 'accent',
  amp: 'neutral',
  pterodactyl: 'online',
  bare_metal: 'warn',
}

const statusTone: Record<string, 'online' | 'warn' | 'offline'> = {
  connected: 'online',
  degraded: 'warn',
  offline: 'offline',
}

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

  if (statusFilter.value !== 'all') {
    result = result.filter(s => s.connection_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<ServerEntry[]>(path)
    servers.value = data
  } catch {
    // API not wired yet
  } finally {
    isLoading.value = false
  }
}

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

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

<template>
  <div class="pas">
    <!-- Page head -->
    <div class="pas__head">
      <div class="pas__head-id">
        <div class="pas__chip">
          <Icon name="server" :size="20" :stroke-width="2" />
        </div>
        <div>
          <div class="t-eyebrow">Platform admin</div>
          <h1 class="pas__title">Server overview</h1>
        </div>
      </div>
    </div>

    <!-- Filters -->
    <div class="pas__filters">
      <Input
        v-model="searchQuery"
        placeholder="Search by server name, email, or IP"
        icon="search"
        style="flex: 1; max-width: 360px"
      />
      <Select
        v-model="statusFilter"
        :options="statusOptions"
      />
    </div>

    <!-- Table -->
    <Panel :flush-body="true" :subtitle="filteredServers.length + ' server' + (filteredServers.length !== 1 ? 's' : '') + (statusFilter !== 'all' ? ' · ' + statusFilter : '')">
      <table class="pas__table">
        <thead>
          <tr class="pas__thead-row">
            <th class="pas__th">Server name</th>
            <th class="pas__th">Owner email</th>
            <th class="pas__th">Connection type</th>
            <th class="pas__th">Status</th>
            <th class="pas__th">Server IP</th>
            <th class="pas__th">Game port</th>
            <th class="pas__th">Last heartbeat</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="isLoading">
            <td colspan="7" class="pas__td-empty">Loading servers...</td>
          </tr>
          <tr v-else-if="filteredServers.length === 0">
            <td colspan="7" class="pas__td-es">
              <EmptyState
                icon="server"
                :title="searchQuery ? 'No matching servers' : (statusFilter !== 'all' ? 'No ' + statusFilter + ' servers' : 'No servers found')"
                :description="searchQuery ? 'Try a different search term.' : 'Servers will appear here once connected.'"
              />
            </td>
          </tr>
          <tr
            v-for="srv in filteredServers"
            :key="srv.license_id"
            class="pas__tr"
          >
            <td class="pas__td pas__td--primary">{{ srv.server_name ?? 'Unnamed' }}</td>
            <td class="pas__td pas__td--secondary">{{ srv.owner_email }}</td>
            <td class="pas__td">
              <Badge :tone="connTypeTone[srv.connection_type] ?? 'neutral'">
                {{ srv.connection_type.replace('_', ' ') }}
              </Badge>
            </td>
            <td class="pas__td">
              <div class="pas__status">
                <StatusDot :tone="statusTone[srv.connection_status] ?? 'neutral'" :pulse="srv.connection_status === 'connected'" />
                <span class="pas__status-label" :data-tone="srv.connection_status">{{ srv.connection_status }}</span>
              </div>
            </td>
            <td class="pas__td pas__td--mono">{{ srv.server_ip ?? '—' }}</td>
            <td class="pas__td pas__td--mono">{{ srv.game_port ?? '—' }}</td>
            <td class="pas__td pas__td--secondary">
              {{ srv.plugin_last_seen
                  ? relativeTime(srv.plugin_last_seen)
                  : srv.companion_last_seen
                    ? relativeTime(srv.companion_last_seen)
                    : 'Never' }}
            </td>
          </tr>
        </tbody>
      </table>
    </Panel>
  </div>
</template>

<style scoped>
.pas { max-width: 1200px; margin: 0 auto; display: flex; flex-direction: column; gap: 16px; }

/* Page head */
.pas__head { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px; }
.pas__head-id { display: flex; align-items: center; gap: 12px; }
.pas__chip {
  width: 40px; height: 40px; flex: none; border-radius: var(--radius-md);
  display: flex; align-items: center; justify-content: center;
  color: var(--accent); background: var(--accent-soft);
  box-shadow: inset 0 0 0 1px var(--accent-border);
}
.pas__title {
  font-size: var(--text-2xl); font-weight: 700; letter-spacing: -0.02em;
  color: var(--text-primary); margin-top: 3px;
}

/* Filters */
.pas__filters { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }

/* Table */
.pas__table { width: 100%; border-collapse: collapse; }
.pas__thead-row { border-bottom: 1px solid var(--border-subtle); }
.pas__th {
  padding: 10px 16px; text-align: left;
  font-size: var(--text-xs); font-weight: 600; color: var(--text-tertiary);
  text-transform: uppercase; letter-spacing: var(--tracking-wider);
  white-space: nowrap;
}
.pas__tr { border-bottom: 1px solid var(--border-subtle); transition: var(--transition-colors); }
.pas__tr:last-child { border-bottom: 0; }
.pas__tr:hover { background: var(--surface-hover); }
.pas__td { padding: 11px 16px; font-size: var(--text-sm); color: var(--text-primary); }
.pas__td--primary { font-weight: 500; }
.pas__td--secondary { color: var(--text-secondary); }
.pas__td--mono { font-family: var(--font-mono); font-variant-numeric: tabular-nums; font-size: var(--text-xs); color: var(--text-secondary); }
.pas__td-empty { padding: 12px 16px; text-align: center; font-size: var(--text-sm); color: var(--text-tertiary); }
.pas__td-es { padding: 0; }

/* Status cell */
.pas__status { display: flex; align-items: center; gap: 7px; }
.pas__status-label { font-size: var(--text-sm); color: var(--text-secondary); }
.pas__status-label[data-tone="connected"] { color: var(--status-online); }
.pas__status-label[data-tone="degraded"] { color: var(--status-warn); }
.pas__status-label[data-tone="offline"] { color: var(--status-offline); }
</style>
