<script setup lang="ts">
import type { ExecutionLogEntry } from '#/api/ai-platform/ai-platform';

import { $t } from '@vben/locales';

import { ElEmpty, ElScrollbar, ElTimeline, ElTimelineItem } from 'element-plus';

import RunStatusTag from './RunStatusTag.vue';

defineProps<{
  activeNodeId?: string;
  logs: ExecutionLogEntry[];
}>();

const emit = defineEmits<{
  select: [nodeId: string];
}>();

function formatDuration(ms?: number) {
  if (!ms && ms !== 0) return '-';
  if (ms < 1000) return `${ms}ms`;
  return `${(ms / 1000).toFixed(2)}s`;
}
</script>

<template>
  <ElScrollbar class="h-full">
    <ElEmpty
      v-if="logs.length === 0"
      :description="$t('ai-platform.workflowRuns.detail.noLogs')"
    />
    <ElTimeline v-else class="px-2 py-3">
      <ElTimelineItem
        v-for="(log, index) in logs"
        :key="`${log.node_id}-${index}`"
        :timestamp="formatDuration(log.elapsed_time)"
        placement="top"
      >
        <button
          type="button"
          class="hover:bg-muted w-full rounded border px-3 py-2 text-left transition-colors"
          :class="activeNodeId === log.node_id ? 'border-primary bg-primary/5' : 'border-border'"
          @click="emit('select', log.node_id)"
        >
          <div class="mb-1 flex items-center justify-between gap-2">
            <span class="text-foreground text-sm font-medium">
              {{ log.node_label || log.node_id }}
            </span>
            <RunStatusTag :status="log.status" />
          </div>
          <div class="text-muted-foreground text-xs">
            {{ log.node_type }}
          </div>
          <div
            v-if="log.error"
            class="text-destructive mt-1 line-clamp-2 text-xs"
          >
            {{ log.error }}
          </div>
        </button>
      </ElTimelineItem>
    </ElTimeline>
  </ElScrollbar>
</template>
