<script setup lang="ts">
import { onBeforeUnmount, onMounted, computed } from "vue";
import { storeToRefs } from "pinia";
import { Trash2, ArrowDown, ArrowUp } from "lucide-vue-next";
import AddPeerDialog from "@/components/AddPeerDialog.vue";
import Stat from "@/components/Stat.vue";
import { usePeersStore } from "@/stores/peers";
import { useNodeStore } from "@/stores/node";
import { endpointString, type ConnectionState } from "@/lib/api";
import { formatBytes } from "@/lib/utils";

const peersStore = usePeersStore();
const node = useNodeStore();
const { peers, stats, error } = storeToRefs(peersStore);
const { phase } = storeToRefs(node);

const isReady = computed(() => phase.value === "ready");

onMounted(async () => {
  await peersStore.bootstrap();
  if (isReady.value) {
    await peersStore.refresh();
  }
});

onBeforeUnmount(() => {
  peersStore.dispose();
});

function badgeFor(state: ConnectionState): string {
  switch (state) {
    case "alive":
      return "bg-emerald-500/15 text-emerald-500 border-emerald-500/30";
    case "connecting":
      return "bg-yellow-500/15 text-yellow-500 border-yellow-500/30";
    case "dead":
      return "bg-destructive/15 text-destructive border-destructive/30";
    default:
      return "bg-muted text-muted-foreground border-border";
  }
}

async function remove(endpoint: string) {
  if (!confirm(`Remove ${endpoint}?`)) return;
  try {
    await peersStore.remove(endpoint);
  } catch (e) {
    alert(`Could not remove peer: ${e}`);
  }
}
</script>

<template>
  <div class="space-y-4">
    <div class="flex flex-wrap items-center gap-3">
      <Stat label="Peers" :value="String(stats.peersTotal)" />
      <Stat label="Alive" :value="String(stats.peersAlive)" tone="alive" />
      <Stat
        label="Connecting"
        :value="String(stats.peersConnecting)"
        tone="connecting"
      />
      <Stat label="Dead" :value="String(stats.peersDead)" tone="dead" />
      <div class="ml-auto">
        <AddPeerDialog />
      </div>
    </div>

    <div class="flex gap-3 text-xs text-muted-foreground">
      <span class="inline-flex items-center gap-1">
        <ArrowDown class="h-3 w-3" /> {{ formatBytes(stats.rxBytes) }}
      </span>
      <span class="inline-flex items-center gap-1">
        <ArrowUp class="h-3 w-3" /> {{ formatBytes(stats.txBytes) }}
      </span>
    </div>

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

    <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">Endpoint</th>
            <th class="px-4 py-2 text-left font-medium">Type</th>
            <th class="px-4 py-2 text-left font-medium">State</th>
            <th class="px-4 py-2 text-right font-medium">RX</th>
            <th class="px-4 py-2 text-right font-medium">TX</th>
            <th class="px-4 py-2"></th>
          </tr>
        </thead>
        <tbody class="divide-y divide-border">
          <tr v-if="!peers.length">
            <td colspan="6" class="px-4 py-8 text-center text-muted-foreground">
              {{
                isReady
                  ? "No peers yet — add one to get started."
                  : "Daemon offline."
              }}
            </td>
          </tr>
          <tr
            v-for="peer in peers"
            :key="endpointString(peer.endpoint)"
            class="hover:bg-muted/30"
          >
            <td class="px-4 py-2 font-mono text-xs break-all">
              {{ endpointString(peer.endpoint) }}
            </td>
            <td class="px-4 py-2">
              <span class="text-xs text-muted-foreground">{{ peer.type }}</span>
            </td>
            <td class="px-4 py-2">
              <span
                class="inline-block rounded-full border px-2 py-0.5 text-xs"
                :class="badgeFor(peer.connectionState)"
              >
                {{ peer.connectionState }}
              </span>
            </td>
            <td class="px-4 py-2 text-right font-mono text-xs">
              {{ formatBytes(peer.rxBytes) }}
            </td>
            <td class="px-4 py-2 text-right font-mono text-xs">
              {{ formatBytes(peer.txBytes) }}
            </td>
            <td class="px-4 py-2 text-right">
              <button
                class="rounded p-1 text-muted-foreground hover:bg-destructive/10 hover:text-destructive"
                title="Remove peer"
                @click="remove(endpointString(peer.endpoint))"
              >
                <Trash2 class="h-4 w-4" />
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>
