<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { Server, Users, Activity, TrendingUp, Search } from 'lucide-vue-next'
import { useApi } from '@/composables/useApi'
import { safeFixed } from '@/utils/formatters'

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 getStatusColor(status: string) {
  switch (status) {
    case 'online':
      return 'bg-green-500'
    case 'degraded':
      return 'bg-yellow-500'
    default:
      return 'bg-red-500'
  }
}

function getStatusText(status: string) {
  switch (status) {
    case 'online':
      return 'Online'
    case 'degraded':
      return 'Degraded'
    default:
      return 'Offline'
  }
}

function getUptimeBadgeColor(uptime: number) {
  if (uptime >= 99) return 'bg-green-500/10 text-green-400'
  if (uptime >= 95) return 'bg-yellow-500/10 text-yellow-400'
  return 'bg-red-500/10 text-red-400'
}

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="min-h-screen bg-neutral-950">
    <!-- Header -->
    <header class="bg-neutral-900 border-b border-neutral-800">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
        <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
          <div>
            <h1 class="text-3xl font-bold text-neutral-100 flex items-center gap-3">
              <Activity class="w-8 h-8 text-oxide-500" />
              Corrosion Status
            </h1>
            <p class="text-neutral-400 mt-1">
              Real-time status for all Corrosion-powered Rust servers
            </p>
          </div>

          <!-- Search -->
          <div class="relative w-full md:w-80">
            <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 servers..."
              class="w-full pl-10 pr-4 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>
        </div>

        <!-- Platform Health Stats -->
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mt-6" v-if="!loading">
          <div class="bg-neutral-800 rounded-lg p-4 border border-neutral-700">
            <div class="flex items-center gap-2 text-neutral-400 text-xs mb-1">
              <Server class="w-3.5 h-3.5" />
              Total Servers
            </div>
            <p class="text-2xl font-bold text-neutral-100">
              {{ platformHealth.total_servers }}
            </p>
          </div>

          <div class="bg-neutral-800 rounded-lg p-4 border border-neutral-700">
            <div class="flex items-center gap-2 text-neutral-400 text-xs mb-1">
              <Activity class="w-3.5 h-3.5" />
              Online Now
            </div>
            <p class="text-2xl font-bold text-green-400">
              {{ platformHealth.online_servers }}
            </p>
          </div>

          <div class="bg-neutral-800 rounded-lg p-4 border border-neutral-700">
            <div class="flex items-center gap-2 text-neutral-400 text-xs mb-1">
              <Users class="w-3.5 h-3.5" />
              Total Players
            </div>
            <p class="text-2xl font-bold text-oxide-400">
              {{ platformHealth.total_players }}
            </p>
          </div>

          <div class="bg-neutral-800 rounded-lg p-4 border border-neutral-700">
            <div class="flex items-center gap-2 text-neutral-400 text-xs mb-1">
              <TrendingUp class="w-3.5 h-3.5" />
              Platform Uptime
            </div>
            <p class="text-2xl font-bold text-neutral-100">
              {{ safeFixed(platformHealth.uptime_percent, 1) }}%
            </p>
          </div>
        </div>
      </div>
    </header>

    <!-- Server Grid -->
    <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
      <!-- Loading State -->
      <div v-if="loading" class="text-center py-12">
        <div class="inline-block w-8 h-8 border-4 border-oxide-500/20 border-t-oxide-500 rounded-full animate-spin"></div>
        <p class="text-neutral-400 mt-4">Loading server status...</p>
      </div>

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

      <!-- Empty State -->
      <div v-else-if="filteredServers.length === 0" class="text-center py-12">
        <Server class="w-16 h-16 text-neutral-600 mx-auto mb-4" />
        <p class="text-neutral-400 text-lg">
          {{ searchQuery ? 'No servers match your search' : 'No servers available yet' }}
        </p>
      </div>

      <!-- Server Cards -->
      <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <div
          v-for="server in filteredServers"
          :key="server.subdomain"
          class="bg-neutral-900 border border-neutral-800 rounded-lg p-5 hover:border-oxide-500/50 transition-colors"
        >
          <!-- Server Header -->
          <div class="flex items-start justify-between mb-4">
            <div class="flex-1 min-w-0">
              <h3 class="text-lg font-semibold text-neutral-100 truncate">
                {{ server.server_name }}
              </h3>
              <a
                :href="`https://${server.subdomain}.corrosionmgmt.com`"
                target="_blank"
                class="text-xs text-oxide-400 hover:text-oxide-300 truncate block"
              >
                {{ server.subdomain }}.corrosionmgmt.com
              </a>
            </div>

            <!-- Status Indicator -->
            <div class="flex items-center gap-2 ml-3">
              <div
                :class="getStatusColor(server.status)"
                class="w-2.5 h-2.5 rounded-full animate-pulse"
              ></div>
              <span class="text-xs font-medium text-neutral-300">
                {{ getStatusText(server.status) }}
              </span>
            </div>
          </div>

          <!-- Description -->
          <p v-if="server.description" class="text-sm text-neutral-400 mb-4 line-clamp-2">
            {{ server.description }}
          </p>

          <!-- Player Count -->
          <div class="flex items-center gap-2 mb-4">
            <Users class="w-4 h-4 text-neutral-500" />
            <span class="text-sm text-neutral-300">
              {{ server.player_count }} / {{ server.max_players }} players
            </span>
            <div class="flex-1 bg-neutral-800 rounded-full h-1.5 overflow-hidden">
              <div
                class="h-full bg-oxide-500 transition-all duration-300"
                :style="{ width: `${(server.player_count / server.max_players) * 100}%` }"
              ></div>
            </div>
          </div>

          <!-- Map Info -->
          <div v-if="server.map_name" class="text-xs text-neutral-500 mb-3">
            Map: {{ server.map_name }}
          </div>

          <!-- Wipe Schedule -->
          <div v-if="server.wipe_schedule" class="bg-neutral-800 rounded-lg p-3 mb-3">
            <div class="text-xs text-neutral-500 mb-1">Wipe Schedule</div>
            <div class="text-sm text-neutral-300">{{ server.wipe_schedule }}</div>
            <div v-if="server.next_wipe" class="text-xs text-oxide-400 mt-1">
              Next wipe: {{ formatTimeUntil(server.next_wipe) }}
            </div>
          </div>

          <!-- Uptime Badges -->
          <div class="flex gap-2">
            <div :class="getUptimeBadgeColor(server.uptime_24h_percent)" class="flex-1 rounded-lg px-2 py-1.5 text-center">
              <div class="text-xs font-medium">{{ safeFixed(server.uptime_24h_percent, 1) }}%</div>
              <div class="text-[10px] opacity-75">24h</div>
            </div>
            <div :class="getUptimeBadgeColor(server.uptime_7d_percent)" class="flex-1 rounded-lg px-2 py-1.5 text-center">
              <div class="text-xs font-medium">{{ safeFixed(server.uptime_7d_percent, 1) }}%</div>
              <div class="text-[10px] opacity-75">7d</div>
            </div>
            <div :class="getUptimeBadgeColor(server.uptime_30d_percent)" class="flex-1 rounded-lg px-2 py-1.5 text-center">
              <div class="text-xs font-medium">{{ safeFixed(server.uptime_30d_percent, 1) }}%</div>
              <div class="text-[10px] opacity-75">30d</div>
            </div>
          </div>
        </div>
      </div>

      <!-- Auto-refresh indicator -->
      <div class="text-center mt-8 text-xs text-neutral-600">
        Auto-refreshing every 10 seconds
      </div>
    </main>

    <!-- Footer -->
    <footer class="bg-neutral-900 border-t border-neutral-800 mt-16">
      <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8 text-center">
        <p class="text-neutral-400 text-sm mb-2">
          Powered by
          <a
            href="https://panel.corrosionmgmt.com"
            class="text-oxide-400 hover:text-oxide-300 font-medium"
            target="_blank"
          >
            Corrosion
          </a>
        </p>
        <p class="text-neutral-600 text-xs">
          The complete server management platform for Rust game servers
        </p>
      </div>
    </footer>
  </div>
</template>
