<script lang="ts">
  import { onMount } from 'svelte'
  import { fetchAudit, type AuditEntry } from '$lib/api'
  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 { Button } from '$lib/components/ui/button'
  import { ScrollArea } from '$lib/components/ui/scroll-area'

  let entries = $state<AuditEntry[]>([])
  let actorFilter = $state('all')
  let actionFilter = $state('')
  let entityFilter = $state('')

  async function load() {
    entries = await fetchAudit({
      actor_type: actorFilter !== 'all' ? actorFilter : undefined,
      action: actionFilter || undefined,
      entity_id: entityFilter || undefined
    })
  }

  onMount(() => {
    load()
    const interval = setInterval(load, 30000)
    return () => clearInterval(interval)
  })

  function actorVariant(actor: string): 'default' | 'secondary' | 'outline' {
    if (actor === 'agent') return 'secondary'
    if (actor === 'operator') return 'default'
    if (actor === 'scheduler') return 'outline'
    return 'outline'
  }

  function methodBadge(method?: string | null): string {
    if (!method) return ''
    if (method === 'GET' || method === 'POST' || method === 'PATCH' || method === 'DELETE') return method
    return ''
  }

  function statusVariant(code?: number | null): 'default' | 'destructive' | 'secondary' | 'outline' {
    if (!code) return 'outline'
    if (code >= 200 && code < 300) return 'default'
    if (code >= 400 && code < 500) return 'secondary'
    if (code >= 500) 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">Audit trail</h1>
    <span class="text-xs text-muted-foreground">{entries.length} entries</span>
  </div>

  <div class="flex gap-2">
    <Select.Root type="single" bind:value={actorFilter} onvalueChange={() => load()}>
      <Select.Trigger class="w-36">
        {actorFilter === 'all' ? 'All actors' : actorFilter}
      </Select.Trigger>
      <Select.Content>
        <Select.Item value="all">All actors</Select.Item>
        <Select.Item value="agent">Agent</Select.Item>
        <Select.Item value="operator">Operator</Select.Item>
        <Select.Item value="system">System</Select.Item>
        <Select.Item value="scheduler">Scheduler</Select.Item>
      </Select.Content>
    </Select.Root>
    <Input placeholder="Action…" bind:value={actionFilter} class="max-w-32" onchange={load} />
    <Input placeholder="Entity…" bind:value={entityFilter} class="max-w-48" onchange={load} />
    <Button variant="outline" 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 class="w-24">Actor</Table.Head>
            <Table.Head>Action</Table.Head>
            <Table.Head>Entity</Table.Head>
            <Table.Head class="w-20">Method</Table.Head>
            <Table.Head class="w-16">Code</Table.Head>
            <Table.Head>Correlation</Table.Head>
          </Table.Row>
        </Table.Header>
        <Table.Body>
          {#each entries as entry (entry.id)}
            <Table.Row>
              <Table.Cell class="font-mono text-xs text-muted-foreground"
                >{new Date(entry.ts).toLocaleString()}</Table.Cell
              >
              <Table.Cell>
                <div class="flex flex-col gap-0.5">
                  <Badge variant={actorVariant(entry.actor_type)}>{entry.actor_type}</Badge>
                  {#if entry.actor_id}
                    <span class="font-mono text-xs text-muted-foreground">{entry.actor_id}</span>
                  {/if}
                </div>
              </Table.Cell>
              <Table.Cell class="text-xs">{entry.action}</Table.Cell>
              <Table.Cell class="font-mono text-xs text-muted-foreground">{entry.entity_id ?? '—'}</Table.Cell>
              <Table.Cell>
                {#if methodBadge(entry.method)}
                  <Badge variant="outline">{methodBadge(entry.method)}</Badge>
                {:else}
                  <span class="text-muted-foreground">—</span>
                {/if}
              </Table.Cell>
              <Table.Cell>
                {#if entry.status_code}
                  <Badge variant={statusVariant(entry.status_code)}>{entry.status_code}</Badge>
                {:else}
                  <span class="text-muted-foreground">—</span>
                {/if}
              </Table.Cell>
              <Table.Cell class="font-mono text-xs text-muted-foreground">{entry.correlation_id ?? '—'}</Table.Cell>
            </Table.Row>
          {:else}
            <Table.Row>
              <Table.Cell colspan={7} class="text-center text-muted-foreground">No audit entries.</Table.Cell>
            </Table.Row>
          {/each}
        </Table.Body>
      </Table.Root>
    </ScrollArea>
  </div>
</div>
