<script lang="ts">
  import { onMount } from 'svelte'
  import { fetchEntities, type Entity, type EntityHealth } from '$lib/api'
  import { liveEvents, subscribeEvents } from '$lib/stores/events'
  import { relativeTime } from '$lib/utils'
  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 { Skeleton } from '$lib/components/ui/skeleton'
  import EntitySheet from '$lib/components/EntitySheet.svelte'

  let sheetOpen = $state(false)
  let selectedSlug = $state<string | null>(null)

  function openEntity(slug: string) {
    selectedSlug = slug
    sheetOpen = true
  }

  let entities = $state<Entity[]>([])
  let loading = $state(true)
  let query = $state('')
  let typeFilter = $state('all')

  async function load() {
    loading = true
    entities = await fetchEntities()
    loading = false
  }

  onMount(() => {
    load()
    const unsubscribe = subscribeEvents()
    return unsubscribe
  })

  // Live-patch on entity.* events instead of a full refetch.
  $effect(() => {
    const ev = $liveEvents[0]
    if (!ev || !ev.type.startsWith('entity.')) return
    load()
  })

  const types = $derived(Array.from(new Set(entities.map((e) => e.type))).sort())

  const filtered = $derived(
    entities.filter((e) => {
      if (typeFilter !== 'all' && e.type !== typeFilter) return false
      if (query && !e.slug.includes(query) && !e.name.includes(query)) return false
      return true
    })
  )

  function stateVariant(state?: string | null): 'default' | 'secondary' | 'outline' {
    if (!state) return 'outline'
    if (state === 'active' || state === 'healthy') return 'default'
    return 'secondary'
  }

  const healthDot: Record<EntityHealth, string> = {
    healthy: 'bg-success',
    degraded: 'bg-warning',
    down: 'bg-destructive',
    stale: 'bg-warning/50',
    unknown: 'bg-muted-foreground/40'
  }

  function healthTitle(entity: Entity): string {
    if (!entity.health) return 'not monitored'
    if (entity.health === 'stale') return `stale — last checked ${relativeTime(entity.last_check_at)}`
    return `${entity.health} — checked ${relativeTime(entity.last_check_at)}`
  }
</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">Entities</h1>
    <span class="text-xs text-muted-foreground">{filtered.length} of {entities.length}</span>
  </div>

  <div class="flex gap-2">
    <Input placeholder="Filter by slug or name…" bind:value={query} class="max-w-xs" />
    <Select.Root type="single" bind:value={typeFilter}>
      <Select.Trigger class="w-40">
        {typeFilter === 'all' ? 'All types' : typeFilter}
      </Select.Trigger>
      <Select.Content>
        <Select.Item value="all">All types</Select.Item>
        {#each types as type}
          <Select.Item value={type}>{type}</Select.Item>
        {/each}
      </Select.Content>
    </Select.Root>
  </div>

  {#if loading}
    <div class="flex flex-col gap-2">
      {#each Array(8) as _}
        <Skeleton class="h-8 w-full" />
      {/each}
    </div>
  {:else}
    <div class="flex-1 overflow-auto rounded-md border">
      <Table.Root>
        <Table.Header>
          <Table.Row>
            <Table.Head>Slug</Table.Head>
            <Table.Head>Type</Table.Head>
            <Table.Head>Name</Table.Head>
            <Table.Head>State</Table.Head>
            <Table.Head>Health</Table.Head>
          </Table.Row>
        </Table.Header>
        <Table.Body>
          {#each filtered as entity (entity.id)}
            <Table.Row
              class="cursor-pointer"
              onclick={() => openEntity(entity.slug)}
            >
              <Table.Cell class="font-mono text-xs">{entity.slug}</Table.Cell>
              <Table.Cell><Badge variant="outline">{entity.type}</Badge></Table.Cell>
              <Table.Cell>{entity.name}</Table.Cell>
              <Table.Cell>
                {#if entity.state}
                  <Badge variant={stateVariant(entity.state)}>{entity.state}</Badge>
                {:else}
                  <span class="text-muted-foreground">—</span>
                {/if}
              </Table.Cell>
              <Table.Cell>
                {#if entity.health}
                  <span class="flex items-center gap-1.5 text-xs" title={healthTitle(entity)}>
                    <span class="size-2 shrink-0 rounded-full {healthDot[entity.health]}"></span>
                    <span class="text-muted-foreground">{relativeTime(entity.last_check_at)}</span>
                  </span>
                {:else}
                  <span class="text-xs text-muted-foreground">—</span>
                {/if}
              </Table.Cell>
            </Table.Row>
          {:else}
            <Table.Row>
              <Table.Cell colspan={5} class="text-center text-muted-foreground"
                >No entities match this filter.</Table.Cell
              >
            </Table.Row>
          {/each}
        </Table.Body>
      </Table.Root>
    </div>
  {/if}
</div>

<EntitySheet slug={selectedSlug} bind:open={sheetOpen} />
