<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useApi } from '@/composables/useApi'
import { safeFixed } from '@/utils/formatters'
import Panel from '@/components/ds/data/Panel.vue'
import StatCard from '@/components/ds/data/StatCard.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 Alert from '@/components/ds/feedback/Alert.vue'
import EmptyState from '@/components/ds/feedback/EmptyState.vue'
import Input from '@/components/ds/forms/Input.vue'
import Logo from '@/components/ds/brand/Logo.vue'

interface ServerStatus {
  server_name: string
  subdomain: string
  status: 'online' | 'offline' | 'degraded'
  player_count: number
  max_players: number
  uptime_24h_percent: number
  uptime_7d_percent: number
  uptime_30d_percent: number
  map_name: string | null
  wipe_schedule: string | null
  next_wipe: string | null
  description: string | null
}

interface PlatformHealth {
  total_servers: number
  online_servers: number
  total_players: number
  uptime_percent: number
}

interface StatusResponse {
  servers: ServerStatus[]
  platform_health: PlatformHealth
}

const api = useApi()
const servers = ref<ServerStatus[]>([])
const platformHealth = ref<PlatformHealth>({
  total_servers: 0,
  online_servers: 0,
  total_players: 0,
  uptime_percent: 0,
})

const searchQuery = ref('')
const loading = ref(true)
const error = ref<string | null>(null)
let refreshInterval: number | null = null

// Filtered servers based on search
const filteredServers = computed(() => {
  if (!searchQuery.value) return servers.value

  const query = searchQuery.value.toLowerCase()
  return servers.value.filter(
    (s) =>
      s.server_name.toLowerCase().includes(query) ||
      s.subdomain.toLowerCase().includes(query) ||
      s.description?.toLowerCase().includes(query)
  )
})

async function fetchStatus() {
  try {
    const response = await api.get<StatusResponse>('/public/status')
    servers.value = response.servers
    platformHealth.value = response.platform_health
    error.value = null
  } catch (err) {
    console.error('Failed to fetch status:', err)
    error.value = 'Failed to load server status'
  } finally {
    loading.value = false
  }
}

function getStatusTone(status: string): 'online' | 'offline' | 'warn' {
  if (status === 'online') return 'online'
  if (status === 'degraded') return 'warn'
  return 'offline'
}

function getUptimeTone(uptime: number): 'online' | 'warn' | 'offline' {
  if (uptime >= 99) return 'online'
  if (uptime >= 95) return 'warn'
  return 'offline'
}

function formatTimeUntil(isoDate: string | null): string {
  if (!isoDate) return 'Not scheduled'

  const now = new Date()
  const target = new Date(isoDate)
  const diff = target.getTime() - now.getTime()

  if (diff < 0) return 'Overdue'

  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))

  if (days > 0) return `${days}d ${hours}h`
  if (hours > 0) return `${hours}h ${minutes}m`
  return `${minutes}m`
}

onMounted(() => {
  fetchStatus()

  // Auto-refresh every 10 seconds
  refreshInterval = window.setInterval(() => {
    fetchStatus()
  }, 10000)
})

onUnmounted(() => {
  if (refreshInterval) {
    clearInterval(refreshInterval)
  }
})
</script>

<template>
  <div class="sp-page">
    <!-- Brand bar -->
    <header class="sp-bar">
      <div class="sp-bar__inner">
        <div class="sp-bar__brand">
          <Logo :size="22" :wordmark="true" />
          <div class="sp-bar__sub">Real-time status for all Corrosion-powered servers</div>
        </div>
        <div class="sp-bar__search">
          <Input
            v-model="searchQuery"
            icon="search"
            placeholder="Search servers..."
            size="sm"
          />
        </div>
      </div>
    </header>

    <!-- Platform KPIs -->
    <div v-if="!loading" class="sp-kpis">
      <StatCard icon="server"       label="Total servers"   :value="String(platformHealth.total_servers)" />
      <StatCard icon="activity"     label="Online now"       :value="String(platformHealth.online_servers)" />
      <StatCard icon="users"        label="Total players"    :value="String(platformHealth.total_players)" />
      <StatCard icon="trending-up"  label="Platform uptime"  :value="safeFixed(platformHealth.uptime_percent, 1)" unit="%" />
    </div>

    <!-- Body -->
    <main class="sp-main">
      <!-- Loading -->
      <div v-if="loading" class="sp-state">
        <Icon name="loader" :size="28" class="sp-spin" />
        <span class="sp-state__label">Loading server status...</span>
      </div>

      <!-- Error -->
      <Alert v-else-if="error" tone="danger" :title="error ?? ''" />

      <!-- Empty -->
      <EmptyState
        v-else-if="filteredServers.length === 0"
        icon="server"
        :title="searchQuery ? 'No servers match your search' : 'No servers available yet'"
      />

      <!-- Server grid -->
      <div v-else class="sp-grid">
        <Panel
          v-for="server in filteredServers"
          :key="server.subdomain"
          class="sp-card"
        >
          <div class="sp-card__body">
            <!-- Server name + link -->
            <div class="sp-card__head">
              <div class="sp-card__name-block">
                <h3 class="sp-card__name">{{ server.server_name }}</h3>
                <a
                  :href="`https://${server.subdomain}.corrosionmgmt.com`"
                  target="_blank"
                  class="sp-card__link"
                >
                  <Icon name="external-link" :size="11" />
                  {{ server.subdomain }}.corrosionmgmt.com
                </a>
              </div>
              <StatusDot :tone="getStatusTone(server.status)" :size="10" :pulse="server.status === 'online'" />
            </div>

            <!-- Description -->
            <p v-if="server.description" class="sp-card__desc">{{ server.description }}</p>

            <!-- Player bar -->
            <div class="sp-players">
              <div class="sp-players__label">
                <Icon name="users" :size="12" />
                <span>{{ server.player_count }} / {{ server.max_players }} players</span>
              </div>
              <div class="sp-players__track">
                <div
                  class="sp-players__fill"
                  :style="{ width: `${(server.player_count / server.max_players) * 100}%` }"
                />
              </div>
            </div>

            <!-- Map -->
            <div v-if="server.map_name" class="sp-card__meta">
              <Icon name="map" :size="12" />
              <span>{{ server.map_name }}</span>
            </div>

            <!-- Wipe schedule -->
            <div v-if="server.wipe_schedule" class="sp-wipe">
              <div class="sp-wipe__label">Wipe schedule</div>
              <div class="sp-wipe__val">{{ server.wipe_schedule }}</div>
              <div v-if="server.next_wipe" class="sp-wipe__next">
                Next: {{ formatTimeUntil(server.next_wipe) }}
              </div>
            </div>

            <!-- Uptime badges -->
            <div class="sp-uptime">
              <Badge :tone="getUptimeTone(server.uptime_24h_percent)" :mono="true" size="lg">
                {{ safeFixed(server.uptime_24h_percent, 1) }}% <span class="sp-uptime__period">24h</span>
              </Badge>
              <Badge :tone="getUptimeTone(server.uptime_7d_percent)" :mono="true" size="lg">
                {{ safeFixed(server.uptime_7d_percent, 1) }}% <span class="sp-uptime__period">7d</span>
              </Badge>
              <Badge :tone="getUptimeTone(server.uptime_30d_percent)" :mono="true" size="lg">
                {{ safeFixed(server.uptime_30d_percent, 1) }}% <span class="sp-uptime__period">30d</span>
              </Badge>
            </div>
          </div>
        </Panel>
      </div>

      <!-- Auto-refresh note -->
      <div class="sp-refresh-note">Auto-refreshing every 10 seconds</div>
    </main>
  </div>
</template>

<style scoped>
.sp-page {
  min-height: 100vh;
  background: var(--surface-canvas);
  display: flex;
  flex-direction: column;
}

/* Brand bar */
.sp-bar {
  background: var(--surface-base);
  box-shadow: 0 1px 0 var(--border-subtle);
  position: sticky;
  top: 0;
  z-index: 20;
}

.sp-bar__inner {
  max-width: 1200px;
  margin: 0 auto;
  padding: var(--space-5) var(--space-6);
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: var(--space-5);
  flex-wrap: wrap;
}

.sp-bar__brand {
  display: flex;
  flex-direction: column;
  gap: var(--space-1);
}

.sp-bar__sub {
  font-size: var(--text-xs);
  color: var(--text-muted);
}

.sp-bar__search {
  width: 260px;
  flex: none;
}

/* Platform KPIs */
.sp-kpis {
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
  padding: var(--space-5) var(--space-6) 0;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: var(--space-3);
}

/* Main content area */
.sp-main {
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
  padding: var(--space-5) var(--space-6) var(--space-8);
  flex: 1;
}

/* Loading state */
.sp-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: var(--space-4);
  padding: var(--space-16) 0;
}

.sp-spin {
  color: var(--accent);
  animation: sp-rotate 0.7s linear infinite;
}

@keyframes sp-rotate {
  to { transform: rotate(360deg); }
}

@media (prefers-reduced-motion: reduce) {
  .sp-spin { animation: none; }
}

.sp-state__label {
  font-size: var(--text-sm);
  color: var(--text-tertiary);
}

/* Server grid */
.sp-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: var(--space-4);
  margin-top: var(--space-5);
}

/* Server card body */
.sp-card__body {
  display: flex;
  flex-direction: column;
  gap: var(--space-3);
}

.sp-card__head {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: var(--space-3);
}

.sp-card__name-block {
  display: flex;
  flex-direction: column;
  gap: var(--space-1);
  min-width: 0;
}

.sp-card__name {
  font-size: var(--text-base);
  font-weight: 600;
  color: var(--text-primary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.sp-card__link {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  font-family: var(--font-mono);
  font-size: 11px;
  color: var(--accent-text);
  transition: color var(--dur-fast) var(--ease-standard);
}

.sp-card__link:hover {
  color: var(--accent);
}

.sp-card__desc {
  font-size: var(--text-xs);
  color: var(--text-tertiary);
  line-height: 1.55;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.sp-card__meta {
  display: inline-flex;
  align-items: center;
  gap: var(--space-1-5);
  font-size: var(--text-xs);
  color: var(--text-muted);
}

/* Player progress bar */
.sp-players {
  display: flex;
  flex-direction: column;
  gap: var(--space-1);
}

.sp-players__label {
  display: flex;
  align-items: center;
  gap: var(--space-1-5);
  font-size: var(--text-xs);
  color: var(--text-secondary);
}

.sp-players__track {
  height: 4px;
  background: var(--surface-raised-2);
  border-radius: var(--radius-pill);
  overflow: hidden;
}

.sp-players__fill {
  height: 100%;
  background: var(--accent);
  border-radius: var(--radius-pill);
  transition: width 0.4s var(--ease-standard);
}

/* Wipe schedule block */
.sp-wipe {
  background: var(--surface-raised);
  box-shadow: var(--ring-default);
  border-radius: var(--radius-md);
  padding: var(--space-2-5) var(--space-3);
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.sp-wipe__label {
  font-size: var(--text-xs);
  color: var(--text-muted);
}

.sp-wipe__val {
  font-size: var(--text-xs);
  color: var(--text-secondary);
}

.sp-wipe__next {
  font-family: var(--font-mono);
  font-size: 11px;
  color: var(--accent-text);
  margin-top: 2px;
}

/* Uptime badges row */
.sp-uptime {
  display: flex;
  gap: var(--space-2);
}

.sp-uptime__period {
  opacity: 0.65;
  font-weight: 400;
  margin-left: 4px;
}

/* Auto-refresh note */
.sp-refresh-note {
  text-align: center;
  margin-top: var(--space-8);
  font-size: var(--text-xs);
  color: var(--text-muted);
}

/* Responsive */
@media (max-width: 1100px) {
  .sp-grid { grid-template-columns: repeat(2, 1fr); }
  .sp-kpis { grid-template-columns: repeat(2, 1fr); }
}

@media (max-width: 640px) {
  .sp-grid { grid-template-columns: 1fr; }
  .sp-kpis { grid-template-columns: repeat(2, 1fr); }
  .sp-bar__search { width: 100%; }
}
</style>
