<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted, ref } from "vue";
import { storeToRefs } from "pinia";
import { TabsRoot, TabsList, TabsTrigger, TabsContent } from "radix-vue";
import RouteTable from "@/components/RouteTable.vue";
import { useRoutesStore } from "@/stores/routes";
import { useNodeStore } from "@/stores/node";
import type { QueriedSubnet } from "@/lib/api";

const routesStore = useRoutesStore();
const node = useNodeStore();
const { snapshot, error } = storeToRefs(routesStore);
const { phase } = storeToRefs(node);

const isReady = computed(() => phase.value === "ready");
const tab = ref<"selected" | "fallback" | "queried">("selected");

// Drives the per-second refresh of the queried-subnet countdown without
// mutating the store; we just read tick.value inside expiresIn().
const tick = ref(0);
let timer: ReturnType<typeof setInterval> | null = null;

onMounted(async () => {
  await routesStore.bootstrap();
  if (isReady.value) await routesStore.refresh();
  timer = setInterval(() => (tick.value += 1), 1000);
});

onBeforeUnmount(() => {
  routesStore.dispose();
  if (timer) clearInterval(timer);
});

function expiresIn(expiration: string): string {
  void tick.value;
  const ms = Date.parse(expiration);
  if (!Number.isFinite(ms)) return expiration;
  const delta = Math.round((ms - Date.now()) / 1000);
  if (delta <= 0) return "expired";
  if (delta < 60) return `${delta}s`;
  if (delta < 3600) return `${Math.floor(delta / 60)}m ${delta % 60}s`;
  return `${Math.floor(delta / 3600)}h ${Math.floor((delta % 3600) / 60)}m`;
}

function queryKey(q: QueriedSubnet): string {
  return `${q.subnet}|${q.expiration}`;
}
</script>

<template>
  <TabsRoot v-model="tab" class="space-y-4">
    <TabsList class="inline-flex rounded-md border border-border bg-card p-1">
      <TabsTrigger
        value="selected"
        class="rounded px-3 py-1.5 text-sm data-[state=active]:bg-secondary data-[state=active]:text-secondary-foreground"
      >
        Selected
        <span class="ml-2 text-xs text-muted-foreground">
          {{ snapshot.selected.length }}
        </span>
      </TabsTrigger>
      <TabsTrigger
        value="fallback"
        class="rounded px-3 py-1.5 text-sm data-[state=active]:bg-secondary data-[state=active]:text-secondary-foreground"
      >
        Fallback
        <span class="ml-2 text-xs text-muted-foreground">
          {{ snapshot.fallback.length }}
        </span>
      </TabsTrigger>
      <TabsTrigger
        value="queried"
        class="rounded px-3 py-1.5 text-sm data-[state=active]:bg-secondary data-[state=active]:text-secondary-foreground"
      >
        Queried
        <span class="ml-2 text-xs text-muted-foreground">
          {{ snapshot.queried.length }}
        </span>
      </TabsTrigger>
    </TabsList>

    <p v-if="error" class="text-sm text-destructive">{{ error }}</p>

    <TabsContent value="selected">
      <RouteTable :rows="snapshot.selected" :ready="isReady" />
    </TabsContent>
    <TabsContent value="fallback">
      <RouteTable :rows="snapshot.fallback" :ready="isReady" />
    </TabsContent>
    <TabsContent value="queried">
      <div class="overflow-hidden rounded-lg border border-border">
        <table class="w-full text-sm">
          <thead class="bg-muted/40 text-xs uppercase text-muted-foreground">
            <tr>
              <th class="px-4 py-2 text-left font-medium">Subnet</th>
              <th class="px-4 py-2 text-left font-medium">Expires in</th>
            </tr>
          </thead>
          <tbody class="divide-y divide-border">
            <tr v-if="!snapshot.queried.length">
              <td colspan="2" class="px-4 py-8 text-center text-muted-foreground">
                {{ isReady ? "No queried subnets." : "Daemon offline." }}
              </td>
            </tr>
            <tr
              v-for="q in snapshot.queried"
              :key="queryKey(q)"
              class="hover:bg-muted/30"
            >
              <td class="px-4 py-2 font-mono text-xs break-all">{{ q.subnet }}</td>
              <td class="px-4 py-2 font-mono text-xs">
                {{ expiresIn(q.expiration) }}
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </TabsContent>
  </TabsRoot>
</template>
