<script lang="ts">
  import type { ToolCallResult } from '$lib/stores/chat'
  import { getExecution } from '$lib/api'
  import LoaderCircleIcon from '@lucide/svelte/icons/loader-circle'
  import CheckIcon from '@lucide/svelte/icons/check'
  import XIcon from '@lucide/svelte/icons/x'
  import ClockIcon from '@lucide/svelte/icons/clock'

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

  const loading = $derived(tool.type === 'tool_use')
  const error = $derived(tool.type === 'tool_result' ? tool.error : undefined)

  const executions = $derived.by(() => {
    if (tool.type !== 'tool_result' || !tool.result) return null
    const data = Array.isArray(tool.result) ? tool.result : (tool.result as any)?.data
    return Array.isArray(data) ? data as any[] : null
  })

  const statusColors: Record<string, string> = {
    completed: 'var(--success)',
    failed: 'var(--destructive)',
    cancelled: 'var(--destructive)',
    denied: 'var(--destructive)',
    revoked: 'var(--destructive)',
    running: 'var(--warning)',
    approved: 'var(--warning)',
    pending_approval: 'var(--muted-foreground)',
    queued: 'var(--muted-foreground)',
  }

  function statusLabel(s: string): string {
    return s.replace(/_/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase())
  }

  function fmtDuration(ms?: number): string {
    if (!ms) return ''
    const s = Math.round(ms / 1000)
    if (s < 60) return `${s}s`
    return `${Math.floor(s / 60)}m ${s % 60}s`
  }

  function truncate(s: string, n: number): string {
    if (!s) return ''
    return s.length > n ? s.slice(0, n) + '…' : s
  }
</script>

{#if loading}
  <div class="flex items-center gap-2 rounded-lg border bg-card px-3 py-2 text-xs" role="status">
    <LoaderCircleIcon class="size-3 shrink-0 animate-spin text-primary" aria-hidden="true" />
    <span class="font-medium">Execution status</span>
    <span class="animate-pulse text-muted-foreground">checking…</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">
    <XIcon class="size-3 shrink-0 text-destructive" aria-hidden="true" />
    <span class="font-medium">Execution status</span>
    <span class="text-destructive">{error}</span>
  </div>
{:else if executions && executions.length > 0}
  <div class="rounded-lg border bg-card text-xs">
    <div class="flex flex-col divide-y">
      {#each executions as exec (exec.execution_id ?? exec.id)}
        {@const status = exec.status ?? 'unknown'}
        {@const color = statusColors[status] ?? 'var(--muted-foreground)'}
        {@const isRunning = status === 'running' || status === 'approved'}
        <div class="flex items-center gap-2 px-3 py-2">
          {#if status === 'completed'}
            <CheckIcon class="size-3 shrink-0" style="color: {color}" aria-hidden="true" />
          {:else if status === 'failed' || status === 'cancelled' || status === 'denied' || status === 'revoked'}
            <XIcon class="size-3 shrink-0" style="color: {color}" aria-hidden="true" />
          {:else if isRunning}
            <LoaderCircleIcon class="size-3 shrink-0 animate-spin" style="color: {color}" aria-hidden="true" />
          {:else}
            <ClockIcon class="size-3 shrink-0 text-muted-foreground" aria-hidden="true" />
          {/if}
          <span class="font-mono font-medium">{truncate(exec.execution_id ?? exec.id ?? '', 12)}</span>
          <span class="text-muted-foreground">{statusLabel(status)}</span>
          {#if exec.action}
            <span class="text-muted-foreground">· {truncate(exec.action, 40)}</span>
          {/if}
          {#if exec.duration_ms}
            <span class="text-muted-foreground">· {fmtDuration(exec.duration_ms)}</span>
          {/if}
          <span class="ml-auto inline-block rounded px-1.5 py-0.5 font-medium text-[10px]" style="background: {color}22; color: {color}">
            {statusLabel(status)}
          </span>
        </div>
        {#if exec.result || exec.error}
          <div class="max-h-32 overflow-y-auto bg-background/60 px-3 py-1.5">
            {#if exec.error}
              <pre class="whitespace-pre-wrap break-all font-mono text-[11px] text-destructive">{exec.error}</pre>
            {:else if exec.result}
              <pre class="whitespace-pre-wrap break-all font-mono text-[11px] text-muted-foreground">{typeof exec.result === 'string' ? exec.result : JSON.stringify(exec.result, null, 2)}</pre>
            {/if}
          </div>
        {/if}
      {/each}
    </div>
  </div>
{:else}
  <div class="flex items-center gap-2 rounded-lg border bg-card px-3 py-2 text-xs" role="status">
    <CheckIcon class="size-3 shrink-0 text-success" aria-hidden="true" />
    <span class="font-medium">Execution status</span>
    <span class="text-muted-foreground">no active executions</span>
  </div>
{/if}
