<script lang="ts">
  import { onMount, onDestroy } from 'svelte'
  import { fetchAgentActivity, type AgentActivity } from '$lib/api'
  import { liveEvents, subscribeEvents } from '$lib/stores/events'
  import * as Table from '$lib/components/ui/table'
  import { Badge } from '$lib/components/ui/badge'
  import { Input } from '$lib/components/ui/input'
  import * as Select from '$lib/components/ui/select'
  import { ScrollArea } from '$lib/components/ui/scroll-area'

  let activities = $state<AgentActivity[]>([])
  let typeFilter = $state('all')
  let agentFilter = $state('')

  async function load() {
    activities = await fetchAgentActivity({
      activity_type: typeFilter !== 'all' ? typeFilter : undefined,
      agent_id: agentFilter || undefined
    })
  }

  onMount(() => {
    load()
    const unsubscribe = subscribeEvents()
    const interval = setInterval(load, 5000)
    return () => {
      unsubscribe()
      clearInterval(interval)
    }
  })

  $effect(() => {
    const ev = $liveEvents[0]
    if (!ev) return
    if (ev.type.startsWith('execution.') || ev.type.startsWith('approval.')) load()
  })

  function typeVariant(type: string): 'default' | 'secondary' | 'outline' {
    if (type === 'tool_call') return 'default'
    if (type === 'decision') return 'secondary'
    if (type === 'escalation') return 'secondary'
    return 'outline'
  }

  function successVariant(success?: boolean | null): 'default' | 'destructive' | 'outline' {
    if (success === true) return 'default'
    if (success === false) return 'destructive'
    return 'outline'
  }
</script>

<div class="flex h-full flex-col gap-4 p-4 md:p-6">
  <div class="flex items-center justify-between">
    <h1 class="text-lg font-semibold">Agent activity</h1>
    <span class="text-xs text-muted-foreground">{activities.length} entries</span>
  </div>

  <div class="flex gap-2">
    <Input placeholder="Filter by agent_id…" bind:value={agentFilter} class="max-w-xs" onchange={load} />
    <Select.Root type="single" bind:value={typeFilter} onvalueChange={() => load()}>
      <Select.Trigger class="w-40">
        {typeFilter === 'all' ? 'All types' : typeFilter}
      </Select.Trigger>
      <Select.Content>
        <Select.Item value="all">All types</Select.Item>
        <Select.Item value="tool_call">Tool call</Select.Item>
        <Select.Item value="reasoning">Reasoning</Select.Item>
        <Select.Item value="decision">Decision</Select.Item>
        <Select.Item value="mcp_query">MCP query</Select.Item>
        <Select.Item value="escalation">Escalation</Select.Item>
      </Select.Content>
    </Select.Root>
    <button type="button" class="rounded-md border px-3 py-1.5 text-xs" onclick={load}>Refresh</button>
  </div>

  <div class="flex-1 overflow-hidden rounded-md border">
    <ScrollArea class="h-full">
      <Table.Root>
        <Table.Header>
          <Table.Row>
            <Table.Head class="w-36">Time</Table.Head>
            <Table.Head>Agent</Table.Head>
            <Table.Head class="w-24">Type</Table.Head>
            <Table.Head>Tool / Entity</Table.Head>
            <Table.Head>Summary</Table.Head>
            <Table.Head class="w-16">Status</Table.Head>
            <Table.Head class="w-20">Duration</Table.Head>
          </Table.Row>
        </Table.Header>
        <Table.Body>
          {#each activities as a (a.id)}
            <Table.Row>
              <Table.Cell class="font-mono text-xs text-muted-foreground"
                >{new Date(a.ts).toLocaleString()}</Table.Cell
              >
              <Table.Cell class="font-mono text-xs">{a.agent_id}</Table.Cell>
              <Table.Cell><Badge variant={typeVariant(a.activity_type)}>{a.activity_type}</Badge></Table.Cell>
              <Table.Cell class="text-xs">
                {#if a.tool_name}
                  <span class="font-mono">{a.tool_name}</span>
                {:else if a.entity_id}
                  <span class="font-mono text-muted-foreground">{a.entity_id}</span>
                {:else}
                  <span class="text-muted-foreground">—</span>
                {/if}
              </Table.Cell>
              <Table.Cell class="max-w-64 truncate text-xs text-muted-foreground"
                >{a.input_summary ?? a.output_summary ?? '—'}</Table.Cell
              >
              <Table.Cell>
                {#if a.success !== undefined && a.success !== null}
                  <Badge variant={successVariant(a.success)}>{a.success ? 'ok' : 'fail'}</Badge>
                {:else}
                  <span class="text-muted-foreground">—</span>
                {/if}
              </Table.Cell>
              <Table.Cell class="text-xs text-muted-foreground">
                {#if a.duration_ms}
                  {(a.duration_ms / 1000).toFixed(1)}s
                {:else}
                  —
                {/if}
              </Table.Cell>
            </Table.Row>
          {:else}
            <Table.Row>
              <Table.Cell colspan={7} class="text-center text-muted-foreground">No agent activity yet.</Table.Cell>
            </Table.Row>
          {/each}
        </Table.Body>
      </Table.Root>
    </ScrollArea>
  </div>
</div>
