<script setup lang="ts">
import { computed, onBeforeUnmount, onMounted } from "vue";
import { storeToRefs } from "pinia";
import { Trash2, RefreshCw } from "lucide-vue-next";
import ComposeMessage from "@/components/ComposeMessage.vue";
import MessageList from "@/components/MessageList.vue";
import { useMessagesStore, type OutboxEntry } from "@/stores/messages";
import { useNodeStore } from "@/stores/node";
import { base64ToUtf8, isPrintableUtf8 } from "@/lib/utils";

const messages = useMessagesStore();
const node = useNodeStore();
const { inbox, outbox } = storeToRefs(messages);
const { phase } = storeToRefs(node);

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

onMounted(async () => {
  await messages.bootstrap();
  if (isReady.value) await messages.refreshInbox();
});

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

async function clearInbox() {
  if (!confirm("Clear all received messages?")) return;
  await messages.clearInbox();
}

function destLabel(d: OutboxEntry["destination"]): string {
  return "ip" in d ? d.ip : d.pk;
}

function topicShort(t: string): string {
  if (!t) return "—";
  return isPrintableUtf8(t) ? base64ToUtf8(t) : `b64:${t.slice(0, 12)}`;
}

async function refreshStatus(id: string) {
  await messages.refreshOutboxStatus(id);
}

async function clearOutbox() {
  if (!confirm("Clear sent message history?")) return;
  await messages.clearOutbox();
}
</script>

<template>
  <div class="grid gap-4 lg:grid-cols-2">
    <section class="space-y-4">
      <ComposeMessage />

      <div class="rounded-lg border border-border bg-card">
        <header class="flex items-center justify-between border-b border-border px-4 py-2">
          <h3 class="text-sm font-medium">Outbox</h3>
          <div class="flex items-center gap-2 text-xs text-muted-foreground">
            <span>{{ outbox.length }}</span>
            <button
              v-if="outbox.length"
              class="rounded p-1 hover:bg-secondary hover:text-foreground"
              title="Clear outbox"
              @click="clearOutbox"
            >
              <Trash2 class="h-4 w-4" />
            </button>
          </div>
        </header>
        <div class="max-h-[35vh] divide-y divide-border overflow-y-auto">
          <p
            v-if="!outbox.length"
            class="px-4 py-6 text-center text-sm text-muted-foreground"
          >
            No sent messages.
          </p>
          <article
            v-for="entry in outbox"
            :key="entry.id"
            class="flex items-start gap-3 px-4 py-2 hover:bg-muted/30"
          >
            <div class="min-w-0 flex-1">
              <div class="flex items-baseline gap-2 text-xs">
                <code class="text-muted-foreground">{{ entry.id }}</code>
                <span class="text-muted-foreground">·</span>
                <span>to <span class="font-mono">{{ destLabel(entry.destination) }}</span></span>
              </div>
              <div class="mt-0.5 truncate text-xs text-muted-foreground">
                topic
                <span class="font-mono">{{ topicShort(entry.topicB64) }}</span>
              </div>
              <div class="mt-0.5 text-xs">
                status:
                <span class="font-mono">{{ entry.status }}</span>
              </div>
            </div>
            <button
              class="shrink-0 rounded p-1 text-muted-foreground hover:bg-secondary hover:text-foreground"
              title="Refresh status"
              @click="refreshStatus(entry.id)"
            >
              <RefreshCw class="h-3.5 w-3.5" />
            </button>
          </article>
        </div>
      </div>
    </section>

    <section>
      <MessageList :messages="inbox" @clear="clearInbox" />
    </section>
  </div>
</template>
