<script setup lang="ts">
import { useRouter } from 'vue-router'

import { Button } from '@/components/ui/button'
import { TableCell, TableRow } from '@/components/ui/table'
import { TooltipWrapper } from '@/components/ui/tooltip'
import { useFormatters } from '@/composables/useFormatters'
import { useNavigation } from '@/composables/useNavigation'
import type { Trace } from '@/types/trace'
import { buildNewTabRouteUrl } from '@/utils/navigation'

const props = withDefaults(
  defineProps<{
    title: string
    traces: Trace[]
    isOpen: boolean
    emptyMessage: string
    showDeleteAction?: boolean
  }>(),
  {
    showDeleteAction: false,
  },
)

const emit = defineEmits<{
  (e: 'toggle'): void
  (e: 'requestDelete', traceId: string): void
}>()

const router = useRouter()
const { goToTrace } = useNavigation()
const { numberFormatter, formatMillis, simpleDateTimeFormatter } = useFormatters()

function formatTime(begin: string | undefined): string {
  if (!begin) return '-'
  return simpleDateTimeFormatter.format(new Date(begin))
}

function traceHref(traceId: string): string {
  const resolved = router.resolve({ name: 'trace', params: { traceId } })
  return buildNewTabRouteUrl(resolved.href, resolved.fullPath)
}

function isInteractiveTarget(target: EventTarget | null): boolean {
  if (!(target instanceof Element)) return false
  return Boolean(target.closest('button, a, input, textarea, select, [role="button"]'))
}

function handleTraceRowClick(event: MouseEvent, traceId: string) {
  if (isInteractiveTarget(event.target)) return

  if (event.metaKey || event.ctrlKey) {
    window.open(traceHref(traceId), '_blank', 'noopener')
    return
  }

  goToTrace(traceId)
}

function handleTraceRowAuxClick(event: MouseEvent, traceId: string) {
  if (isInteractiveTarget(event.target) || event.button !== 1) return
  window.open(traceHref(traceId), '_blank', 'noopener')
}
</script>

<template>
  <TableRow>
    <TableCell colspan="6" class="bg-sidebar-accent p-0">
      <button
        class="w-full flex items-center font-medium text-sm text-left cursor-pointer py-2 pl-2 pr-4"
        @click="emit('toggle')"
      >
        <span>{{ props.title }} ({{ props.traces.length }})</span>
        <i
          class="dku-icon-chevron-right-16 ml-2 transition-transform duration-200"
          :class="props.isOpen && 'rotate-90'"
        />
      </button>
    </TableCell>
  </TableRow>

  <template v-if="props.isOpen">
    <TableRow
      v-for="trace in props.traces"
      :key="trace.id"
      class="cursor-pointer hover:bg-muted/50 group text-sm"
      @click="handleTraceRowClick($event, trace.id)"
      @auxclick="handleTraceRowAuxClick($event, trace.id)"
    >
      <TableCell class="max-w-0 min-w-[200px]">
        <div class="flex items-center gap-2">
          <span class="block truncate text-foreground">
            {{ trace.name || 'No input' }}
          </span>
        </div>
      </TableCell>
      <TableCell class="max-w-0 min-w-[200px]">
        <span class="block truncate text-muted-foreground">
          {{ trace.result || 'No output' }}
        </span>
      </TableCell>
      <TableCell>
        <span class="text-sm">{{ formatTime(trace.begin) }}</span>
      </TableCell>
      <TableCell>
        <span class="text-sm">{{ formatMillis(trace.duration) }}</span>
      </TableCell>
      <TableCell>
        <span v-if="trace.tokens?.totalTokens" class="text-sm">
          {{ trace.tokens.totalTokens ? numberFormatter.format(trace.tokens.totalTokens) : '-' }}
        </span>
        <span v-else class="text-sm">-</span>
      </TableCell>
      <TableCell class="px-2">
        <TooltipWrapper v-if="props.showDeleteAction" content="Delete pasted trace">
          <Button
            variant="ghost"
            size="icon"
            class="h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity text-destructive hover:bg-destructive/20"
            @click.stop="emit('requestDelete', trace.id)"
          >
            <i class="dku-icon-trash-12" />
          </Button>
        </TooltipWrapper>
      </TableCell>
    </TableRow>

    <TableRow v-if="props.traces.length === 0">
      <TableCell colspan="6" class="h-12 text-center text-muted-foreground">
        {{ props.emptyMessage }}
      </TableCell>
    </TableRow>
  </template>
</template>
