<template>
  <div class="flex-grow overflow-hidden">
    <Separator class="opacity-50" />
    <ScrollArea
      class="h-[100%] px-4 py-0 [&_[data-slot='scroll-area-viewport']:focus-visible]:outline-0 [&_[data-slot='scroll-area-viewport']:focus-visible]:ring-0"
      type="scroll"
    >
      <div v-for="item in tracesWithSections" class="my-2">
        <div v-if="typeof item === 'string'">
          <Badge variant="secondary">
            {{ item }}
          </Badge>
        </div>
        <TraceCard
          v-else
          :trace="item"
          :is-selected="item.id == tracesStore.selectedTraceId"
          @click="selectTrace(item.id)"
        />
      </div>
    </ScrollArea>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'

import { API } from '@/Api'
import { useTracesStore } from '@/stores/traces'
import type { Trace } from '@/common/interface/trace'
import { Badge } from '@/components/ui/badge'
import { Separator } from '@/components/ui/separator'
import { ScrollArea } from '@/components/ui/scroll-area'

import TraceCard from './TraceCard.vue'

const tracesStore = useTracesStore()

const tracesWithSections = computed(() => {
  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  const lastWeek = new Date(today)
  lastWeek.setDate(lastWeek.getDate() - 7)
  const lastMonth = new Date(today)
  lastMonth.setMonth(lastMonth.getMonth() - 1)

  const result: (Trace | string)[] = []
  let lastSection: string | null = null

  tracesStore.filteredTraces.forEach((trace) => {
    const traceDate = trace.begin ? new Date(trace.begin) : new Date()
    let section: string

    if (traceDate >= today) {
      section = 'Today'
    } else if (traceDate >= lastWeek) {
      section = 'Last 7 days'
    } else if (traceDate >= lastMonth) {
      section = 'Last 30 days'
    } else if (traceDate.getFullYear() === today.getFullYear()) {
      section = traceDate.toLocaleString('default', { month: 'long' })
    } else {
      section = traceDate.getFullYear().toString()
    }

    if (section !== lastSection) {
      result.push(section)
      lastSection = section
    }

    result.push(trace)
  })

  return result
})

async function selectTrace(traceId: string) {
  tracesStore.selectedNodeId = null
  const selectedTrace = tracesStore.traces.find((trace) => trace.id == traceId)

  if (selectedTrace && !selectedTrace.parentNode) {
    tracesStore.isLoadingTrace = true
    tracesStore.updateDatasetTrace(await API.getTrace(traceId))
  }

  tracesStore.isLoadingTrace = false
  tracesStore.selectedTraceId = traceId
}
</script>
