<script setup lang="ts">
import { watchDebounced } from '@vueuse/core'
import { ref } from 'vue'

import { useFormatters } from '@/composables/useFormatters'
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table'
import {
  AlertDialog,
  AlertDialogAction,
  AlertDialogCancel,
  AlertDialogContent,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogTitle,
} from '@/components/ui/alert-dialog'
import { Button } from '@/components/ui/button'
import { useNavigation } from '@/composables/useNavigation'
import { useUiStore } from '@/stores/uiStore'
import { useTracesStore } from '@/stores/tracesStore'
import { WT1iser } from '@/services/wt1'
import { LOCAL_TRACE_STORAGE_KEY } from '@/utils/config'
import { removeTraceFromLS } from '@/utils/localStorage'
import { Input } from '@/components/ui/input'
import Badge from '@/components/ui/badge/Badge.vue'
import { HelpIcon } from '@/components/ui/help-icon'
import { TooltipWrapper } from '@/components/ui/tooltip'

const uiStore = useUiStore()
const tracesStore = useTracesStore()
const { goToTrace } = useNavigation()
const { numberFormatter, formatMillis, simpleDateTimeFormatter } = useFormatters()

const showDeleteConfirm = ref(false)

watchDebounced(
  () => [uiStore.nameSearchQuery, uiStore.resultSearchQuery],
  ([nameQuery, resultQuery]) => {
    if (nameQuery || resultQuery) {
      WT1iser.searchTraces(nameQuery ?? '', resultQuery ?? '')
    }
  },
  { debounce: 500 },
)

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

function isLocalTrace(traceId: string): boolean {
  return traceId.startsWith(LOCAL_TRACE_STORAGE_KEY)
}

function confirmDeleteLocalTrace() {
  removeTraceFromLS()
  tracesStore.clearLocalTrace()
  showDeleteConfirm.value = false
}
</script>

<template>
  <div class="h-full w-full flex flex-col">
    <!-- Main Table -->
    <div class="border-b border-border">
      <Table>
        <TableHeader>
          <TableRow>
            <TableHead class="py-2 w-[35%]">
              <div class="flex flex-col gap-1.5">
                <div class="flex gap-2 items-center">
                  <span class="font-semibold tracking-wider">User message</span>
                  <HelpIcon content="First user message from the trace inputs" />
                </div>
                <Input
                  v-if="tracesStore.hasApiTraces"
                  v-model="uiStore.nameSearchQuery"
                  placeholder="Filter by user message..."
                  class="h-7 max-w-[350px]"
                />
              </div>
            </TableHead>
            <TableHead class="py-2 w-[35%]">
              <div class="flex flex-col gap-1.5">
                <div class="flex gap-2 items-center">
                  <span class="font-semibold tracking-wider">Response text</span>
                  <HelpIcon content="Text message from the trace output" />
                </div>
                <Input
                  v-if="tracesStore.hasApiTraces"
                  v-model="uiStore.resultSearchQuery"
                  placeholder="Filter by response text..."
                  class="h-7 max-w-[350px]"
                />
              </div>
            </TableHead>
            <TableHead class="py-2 content-end font-semibold tracking-wider w-[12%]">
              Start
            </TableHead>
            <TableHead class="py-2 content-end font-semibold tracking-wider w-[9%]">
              Duration
            </TableHead>
            <TableHead class="py-2 content-end font-semibold tracking-wider w-[6%]">
              Tokens
            </TableHead>
            <!-- Empty header for delete button column -->
            <TableHead class="w-[3%]"></TableHead>
          </TableRow>
        </TableHeader>
        <TableBody class="text-base">
          <TableRow
            v-for="trace in uiStore.filteredTraces"
            :key="trace.id"
            @click="goToTrace(trace.id)"
            class="cursor-pointer hover:bg-muted/50 group"
          >
            <TableCell class="max-w-0">
              <div class="flex items-center gap-2">
                <Badge
                  v-if="isLocalTrace(trace.id)"
                  variant="outline"
                  class="rounded-sm bg-white dark:bg-sidebar"
                >
                  Pasted trace
                </Badge>
                <span class="block truncate text-foreground">
                  {{ trace.name || 'No input' }}
                </span>
              </div>
            </TableCell>
            <TableCell class="max-w-0">
              <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>
            <!-- Delete button for local traces -->
            <TableCell class="px-2">
              <TooltipWrapper v-if="isLocalTrace(trace.id)" 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="showDeleteConfirm = true"
                >
                  <i class="dku-icon-trash-12" />
                </Button>
              </TooltipWrapper>
            </TableCell>
          </TableRow>
          <!-- No traces found -->
          <TableRow v-if="uiStore.filteredTraces.length === 0 && tracesStore.hasApiTraces">
            <TableCell colspan="6" class="h-24 text-center text-muted-foreground">
              No trace matching the filters.
            </TableCell>
          </TableRow>
          <!-- No dataset traces -->
          <TableRow v-if="tracesStore.traces?.data.length === 0 && !tracesStore.localTrace">
            <TableCell colspan="6" class="h-24 text-center text-muted-foreground">
              Paste a new trace or select a dataset in the settings.
            </TableCell>
          </TableRow>
        </TableBody>
      </Table>
    </div>

    <!-- Delete confirmation dialog -->
    <AlertDialog v-model:open="showDeleteConfirm">
      <AlertDialogContent class="p-4">
        <AlertDialogHeader>
          <AlertDialogTitle>Delete pasted trace?</AlertDialogTitle>
          <AlertDialogDescription>
            This will remove the trace. This action cannot be undone.
          </AlertDialogDescription>
        </AlertDialogHeader>
        <AlertDialogFooter>
          <AlertDialogCancel>Cancel</AlertDialogCancel>
          <AlertDialogAction
            class="bg-destructive hover:bg-destructive/90"
            @click="confirmDeleteLocalTrace"
          >
            Delete
          </AlertDialogAction>
        </AlertDialogFooter>
      </AlertDialogContent>
    </AlertDialog>
  </div>
</template>
