<script setup lang="ts">
import { createColumnHelper, getCoreRowModel, useVueTable } from '@tanstack/vue-table'

import { HelpIcon } from '@/components/ui/help-icon'
import { Input } from '@/components/ui/input'
import { TableHead, TableHeader, TableRow } from '@/components/ui/table'
import type {
  TraceListHeaderColumnId,
  TraceListHeaderRow,
  TraceListSortDirection,
  TraceListSortField,
} from '@/types/trace-list'

const props = defineProps<{
  hasApiTraces: boolean
  nameSearchQuery: string
  resultSearchQuery: string
  sortField: TraceListSortField | null
  sortDirection: TraceListSortDirection
}>()

const emit = defineEmits<{
  (e: 'update:nameSearchQuery', value: string): void
  (e: 'update:resultSearchQuery', value: string): void
  (e: 'toggleSort', field: TraceListSortField): void
}>()

const columnHelper = createColumnHelper<TraceListHeaderRow>()
const columns = [
  columnHelper.accessor('name', {
    id: 'name',
    header: 'User message',
  }),
  columnHelper.accessor('result', {
    id: 'result',
    header: 'Response text',
  }),
  columnHelper.accessor('start', {
    id: 'start',
    header: 'Start',
  }),
  columnHelper.accessor('duration', {
    id: 'duration',
    header: 'Duration',
  }),
  columnHelper.accessor('tokens', {
    id: 'tokens',
    header: 'Tokens',
  }),
  columnHelper.display({
    id: 'actions',
    header: '',
  }),
]

const table = useVueTable({
  data: [],
  columns,
  getCoreRowModel: getCoreRowModel(),
})

function isSortedBy(field: TraceListSortField): boolean {
  return props.sortField === field
}

function getHeaderCellClass(columnId: TraceListHeaderColumnId): string {
  if (columnId === 'name') return 'min-w-[200px]'
  if (columnId === 'result') return 'min-w-[200px]'
  if (columnId === 'start') return 'w-[180px] max-w-[180px]'
  if (columnId === 'duration') return 'w-[120px] max-w-[120px]'
  if (columnId === 'tokens') return 'w-[110px] max-w-[110px]'
  if (columnId === 'actions') return 'w-[44px] max-w-[44px]'
  return ''
}
</script>

<template>
  <TableHeader>
    <TableRow v-for="headerGroup in table.getHeaderGroups()" :key="headerGroup.id">
      <TableHead
        v-for="header in headerGroup.headers"
        :key="header.id"
        :class="getHeaderCellClass(header.column.id as TraceListHeaderColumnId)"
      >
        <template v-if="header.column.id === 'name'">
          <div class="flex gap-2 items-center">
            <span class="font-medium">User message</span>
            <HelpIcon content="First user message from the trace inputs" />
          </div>
        </template>

        <template v-else-if="header.column.id === 'result'">
          <div class="flex gap-2 items-center">
            <span class="font-medium">Response text</span>
            <HelpIcon content="Text message from the trace output" />
          </div>
        </template>

        <template v-else-if="header.column.id === 'start'">
          <button
            class="inline-flex items-center gap-1 font-medium cursor-pointer"
            @click="emit('toggleSort', 'start')"
          >
            <span>Start</span>
            <span class="inline-flex items-center">
              <i
                v-if="!isSortedBy('start')"
                class="dku-icon-arrow-sort-16 text-muted-foreground/70"
              />
              <i
                v-else
                class="dku-icon-arrow-right-long-16 text-muted-foreground/70 transition-transform"
                :class="props.sortDirection === 'asc' ? '-rotate-90' : 'rotate-90'"
              />
            </span>
          </button>
        </template>

        <template v-else-if="header.column.id === 'duration'">
          <button
            class="inline-flex items-center gap-1 font-medium cursor-pointer"
            @click="emit('toggleSort', 'duration')"
          >
            <span>Duration</span>
            <span class="inline-flex items-center">
              <i
                v-if="!isSortedBy('duration')"
                class="dku-icon-arrow-sort-16 text-muted-foreground/70"
              />
              <i
                v-else
                class="dku-icon-arrow-right-long-16 text-muted-foreground/70 transition-transform"
                :class="props.sortDirection === 'asc' ? '-rotate-90' : 'rotate-90'"
              />
            </span>
          </button>
        </template>

        <template v-else-if="header.column.id === 'tokens'">
          <button
            class="inline-flex items-center gap-1 font-medium cursor-pointer"
            @click="emit('toggleSort', 'tokens')"
          >
            <span>Tokens</span>
            <span class="inline-flex items-center">
              <i
                v-if="!isSortedBy('tokens')"
                class="dku-icon-arrow-sort-16 text-muted-foreground/70"
              />
              <i
                v-else
                class="dku-icon-arrow-right-long-16 text-muted-foreground/70 transition-transform"
                :class="props.sortDirection === 'asc' ? '-rotate-90' : 'rotate-90'"
              />
            </span>
          </button>
        </template>
      </TableHead>
    </TableRow>

    <TableRow v-for="headerGroup in table.getHeaderGroups()" :key="`${headerGroup.id}-filters`">
      <TableHead
        v-for="header in headerGroup.headers"
        :key="`${header.id}-filters`"
        class="relative p-2 text-left align-top"
        :class="getHeaderCellClass(header.column.id as TraceListHeaderColumnId)"
      >
        <Input
          v-if="props.hasApiTraces && header.column.id === 'name'"
          :model-value="props.nameSearchQuery"
          placeholder="Filter by user message..."
          class="h-7 max-w-[300px]"
          @update:model-value="emit('update:nameSearchQuery', ($event as string) ?? '')"
        />
        <Input
          v-else-if="props.hasApiTraces && header.column.id === 'result'"
          :model-value="props.resultSearchQuery"
          placeholder="Filter by response text..."
          class="h-7 max-w-[300px]"
          @update:model-value="emit('update:resultSearchQuery', ($event as string) ?? '')"
        />
      </TableHead>
    </TableRow>
  </TableHeader>
</template>
