<script setup>
import { computed, ref } from 'vue'
import { useOperationsStore } from '@/stores/operationsStore'
import { usePolling } from '@/composables/usePolling'

const store = useOperationsStore()
const drawerOpen = ref(false)

const tabs = [
  { label: 'All', value: null },
  { label: 'Degraded', value: 'DEGRADED' },
  { label: 'Offline', value: 'OFFLINE' },
]

usePolling(() => store.fetchFleet(), 15_000)

function statusBadgeClass(status) {
  if (status === 'ONLINE') return 'bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-300'
  if (status === 'DEGRADED') return 'bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300'
  return 'bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-300'
}

function formatMinutes(m) {
  if (m == null) return '—'
  return `${Math.round(m)} min ago`
}

async function openDetail(gateway) {
  await store.fetchGatewayDetail(gateway.id)
  drawerOpen.value = true
}
</script>

<template>
  <div class="space-y-8">
    <header class="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
      <h1 class="text-2xl font-semibold text-gray-900 dark:text-gray-100">Gateway Fleet</h1>
      <div class="flex gap-2">
        <button
          v-for="tab in tabs"
          :key="tab.label"
          type="button"
          class="rounded-lg px-4 py-2 text-sm font-medium transition duration-150"
          :class="store.statusFilter === tab.value
            ? 'bg-blue-600 text-white'
            : 'bg-gray-100 text-gray-700 dark:bg-gray-800 dark:text-gray-300'"
          @click="store.setStatusFilter(tab.value)"
        >
          {{ tab.label }}
        </button>
      </div>
    </header>

    <p v-if="store.error" class="text-sm text-red-600">{{ store.error }}</p>

    <div class="overflow-x-auto rounded-lg border border-gray-200 dark:border-gray-800">
      <table class="min-w-full divide-y divide-gray-200 dark:divide-gray-800">
        <thead class="bg-gray-50 dark:bg-gray-900">
          <tr>
            <th class="px-4 py-2 text-left text-sm font-medium">Site</th>
            <th class="px-4 py-2 text-left text-sm font-medium">Gateway</th>
            <th class="px-4 py-2 text-left text-sm font-medium">Department</th>
            <th class="px-4 py-2 text-left text-sm font-medium">Status</th>
            <th class="px-4 py-2 text-left text-sm font-medium">Buffer</th>
            <th class="px-4 py-2 text-left text-sm font-medium">Last Heartbeat</th>
            <th class="px-4 py-2 text-left text-sm font-medium">Last Sync</th>
            <th class="px-4 py-2 text-left text-sm font-medium">Minutes Offline</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-gray-200 dark:divide-gray-800">
          <tr
            v-for="gw in store.fleet"
            :key="gw.id"
            class="cursor-pointer hover:bg-gray-50 dark:hover:bg-gray-900/50"
            @click="openDetail(gw)"
          >
            <td class="px-4 py-2 text-sm">{{ gw.siteName }}</td>
            <td class="px-4 py-2 text-sm font-medium">{{ gw.gatewayCode }}</td>
            <td class="px-4 py-2 text-sm">{{ gw.department }}</td>
            <td class="px-4 py-2">
              <span class="rounded-full px-2 py-1 text-xs font-medium" :class="statusBadgeClass(gw.status)">
                {{ gw.status }}
              </span>
            </td>
            <td class="px-4 py-2 text-sm">{{ gw.reportedBufferDepth }}</td>
            <td class="px-4 py-2 text-sm">{{ formatMinutes(gw.minutesSinceHeartbeat) }}</td>
            <td class="px-4 py-2 text-sm">{{ gw.lastSyncAt ? new Date(gw.lastSyncAt).toLocaleString() : '—' }}</td>
            <td class="px-4 py-2 text-sm">{{ gw.minutesSinceHeartbeat != null ? Math.round(gw.minutesSinceHeartbeat) : '—' }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <aside
      v-if="drawerOpen && store.selectedGateway"
      class="fixed inset-y-0 right-0 z-50 w-full max-w-md border-l border-gray-200 bg-white p-4 shadow-lg dark:border-gray-800 dark:bg-gray-900"
    >
      <button type="button" class="mb-4 text-sm text-blue-600" @click="drawerOpen = false">Close</button>
      <h2 class="mb-4 text-lg font-semibold">{{ store.selectedGateway.gateway.gatewayCode }}</h2>
      <h3 class="mb-2 text-sm font-medium text-gray-500">Recent sync batches</h3>
      <ul class="space-y-2">
        <li
          v-for="batch in store.selectedGateway.recentBatches"
          :key="batch.batchId"
          class="rounded-lg border border-gray-200 p-4 text-sm dark:border-gray-800"
        >
          <span class="font-medium">{{ batch.status }}</span>
          — {{ new Date(batch.submittedAt).toLocaleString() }}
          <span v-if="batch.conflictCount"> ({{ batch.conflictCount }} conflicts)</span>
        </li>
      </ul>
    </aside>
  </div>
</template>