<script setup lang="ts">
import { ref } from 'vue'
import { Panel, TableRenderer } from 'mpr-ui-framework'
import type { TableColumn, DataSource } from 'mpr-ui-framework'

const props = defineProps<{
  source: DataSource
  status?: 'idle' | 'live' | 'processing' | 'error'
  embedded?: boolean
}>()

const columns: TableColumn[] = [
  { key: 'brand', label: 'Brand', width: '120px' },
  { key: 'confidence', label: 'Conf', width: '60px' },
  { key: 'source', label: 'Source', width: '80px' },
  { key: 'timestamp', label: 'Time', width: '60px' },
  { key: 'content_type', label: 'Type', width: '100px' },
  { key: 'frame_ref', label: 'Frame', width: '50px' },
]

const rows = ref<Record<string, unknown>[]>([])
const sortKey = ref('timestamp')
const sortDir = ref<'asc' | 'desc'>('desc')

props.source.on<Record<string, unknown>>('detection', (e) => {
  rows.value.push({
    brand: e.brand,
    confidence: typeof e.confidence === 'number' ? (e.confidence as number).toFixed(2) : e.confidence,
    source: e.source,
    timestamp: typeof e.timestamp === 'number' ? (e.timestamp as number).toFixed(1) : e.timestamp,
    content_type: e.content_type,
    frame_ref: e.frame_ref,
  })
})

function onSort(key: string) {
  if (sortKey.value === key) {
    sortDir.value = sortDir.value === 'asc' ? 'desc' : 'asc'
  } else {
    sortKey.value = key
    sortDir.value = 'desc'
  }
}
</script>

<template>
  <Panel v-if="!embedded" title="Detections" :status="status">
    <TableRenderer
      :columns="columns"
      :rows="rows"
      :sort-key="sortKey"
      :sort-dir="sortDir"
      @sort="onSort"
    />
  </Panel>
  <TableRenderer
    v-else
    :columns="columns"
    :rows="rows"
    :sort-key="sortKey"
    :sort-dir="sortDir"
    @sort="onSort"
  />
</template>
