<script lang="ts">
  import type { ToolCallResult } from '$lib/stores/chat'
  import { Badge } from '$lib/components/ui/badge'
  import { relativeTime } from '$lib/utils'
  import LoaderCircleIcon from '@lucide/svelte/icons/loader-circle'
  import CheckIcon from '@lucide/svelte/icons/check'
  import XIcon from '@lucide/svelte/icons/x'
  import BoxIcon from '@lucide/svelte/icons/box'
  import MonitorIcon from '@lucide/svelte/icons/monitor'
  import ContainerIcon from '@lucide/svelte/icons/container'
  import GlobeIcon from '@lucide/svelte/icons/globe'
  import WrenchIcon from '@lucide/svelte/icons/wrench'
  import ZapIcon from '@lucide/svelte/icons/zap'

  let { tool }: { tool: ToolCallResult } = $props()

  const entity = $derived.by(() => {
    if (tool.type !== 'tool_result') return null
    const r = tool.result
    if (!r) return null
    if (Array.isArray(r)) return r[0]
    if (r && typeof r === 'object' && 'data' in r) return Array.isArray(r.data) ? r.data[0] : r.data
    return r
  })

  const loading = $derived(tool.type === 'tool_use')
  const error = $derived(tool.type === 'tool_result' ? tool.error : undefined)
  const slug = $derived(entity?.slug ?? tool.args?.slug_or_id ?? tool.args?.hostname ?? tool.args?.service_slug ?? '')

  const typeIcon: Record<string, typeof BoxIcon> = {
    host: MonitorIcon,
    lxc: ContainerIcon,
    service: GlobeIcon,
    check: ZapIcon,
  }

  const Icon = $derived(entity?.type ? (typeIcon[entity.type] ?? BoxIcon) : BoxIcon)

  const keyAttrs = $derived.by(() => {
    if (!entity) return [] as [string, string][]
    const out: [string, string][] = []
    const skip = new Set(['slug', 'type', 'name', 'state', 'health', 'last_check', 'version', 'created_at', 'updated_at', 'maintenance_until', '__renderer', 'data', 'attrs', 'attributes', 'enrolled_at'])
    for (const k of ['mesh_ip', 'ip', 'version', 'age_pubkey', 'enrolled_at', 'last_check']) {
      const v = entity[k]
      if (v && typeof v === 'string') {
        out.push([k, k === 'age_pubkey' ? v.slice(0, 16) + '…' : v])
      }
    }
    const attrs = entity.attributes ?? entity.attrs
    if (attrs && typeof attrs === 'object') {
      for (const [k, v] of Object.entries(attrs as Record<string, unknown>)) {
        if (!skip.has(k) && v != null && v !== '') {
          out.push([k, typeof v === 'object' ? JSON.stringify(v) : String(v)])
        }
      }
    }
    return out.slice(0, 4)
  })

  const healthColor: Record<string, string> = {
    healthy: 'var(--success)',
    degraded: 'var(--warning)',
    down: 'var(--destructive)',
  }
</script>

{#if loading}
  <div class="flex items-center gap-2 rounded-lg border bg-card px-3 py-2 text-xs" role="status" aria-label="Loading entity: {slug || tool.name}">
    <LoaderCircleIcon class="size-3 shrink-0 animate-spin text-primary" aria-hidden="true" />
    <span class="font-mono font-medium">{slug || tool.name}</span>
    <span class="animate-pulse text-muted-foreground">loading…</span>
  </div>
{:else if error}
  <div class="flex items-center gap-2 rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-xs" role="alert" aria-label="Error loading entity: {error}">
    <XIcon class="size-3 shrink-0 text-destructive" aria-hidden="true" />
    <span class="font-mono font-medium">{slug || tool.name}</span>
    <span class="text-destructive">{error}</span>
  </div>
{:else if entity}
  <div class="rounded-lg border bg-card px-3 py-2 text-xs" aria-label="Entity: {entity.slug} — {entity.type} — {entity.health || 'no health data'}">


    <div class="flex flex-wrap items-center gap-1.5">
      <div class="flex items-center gap-1.5">
        <Icon class="size-3.5 shrink-0 text-muted-foreground" aria-hidden="true" />
        <span class="font-mono font-semibold">{entity.slug ?? slug}</span>
      </div>
      {#if entity.type}
        <Badge variant="outline" class="text-[10px]">{entity.type}</Badge>
      {/if}
      {#if entity.state}
        <Badge variant="secondary" class="text-[10px]">{entity.state}</Badge>
      {/if}
      {#if entity.health && entity.health !== 'unknown'}
        <span class="flex items-center gap-1 text-muted-foreground">
          <span class="size-2 rounded-full" style="background: {healthColor[entity.health] ?? 'var(--muted-foreground)'}"></span>
          {entity.health}
        </span>
      {/if}
      {#if entity.last_check}
        <span class="text-muted-foreground">· {relativeTime(entity.last_check)}</span>
      {/if}
    </div>
    {#if keyAttrs.length > 0}
      <div class="mt-1.5 flex flex-wrap gap-x-3 gap-y-0.5 text-muted-foreground">
        {#each keyAttrs as [k, v]}
          <span class="font-mono text-[10px]"><span class="opacity-60">{k}:</span> {v}</span>
        {/each}
      </div>
    {/if}
  </div>
{:else}
  <div class="flex items-center gap-2 rounded-lg border bg-card px-3 py-2 text-xs" role="status" aria-label="Entity: {slug || tool.name} — no data">
    <CheckIcon class="size-3 shrink-0 text-success" aria-hidden="true" />
    <span class="font-mono font-medium">{slug || tool.name}</span>
    <span class="text-muted-foreground">no data</span>
  </div>
{/if}
