<template>
  <div class="flex justify-between mt-2">
    <Label>Duration</Label>
    <div class="text-xs flex">
      <Badge variant="secondary" class="mr-1">
        <span>{{ tracesStore.tracesFilters.duration[0] }}ms</span>
        —
        <span>{{ tracesStore.tracesFilters.duration[1] }}ms</span>
      </Badge>
      <ResetFilter :reset-handler="clearDurationFilter" />
    </div>
  </div>
  <div class="flex-grow h-8 flex items-center">
    <Slider
      :min="sliderRange[0]"
      :max="sliderRange[1]"
      :min-steps-between-thumbs="1"
      v-model="tracesStore.tracesFilters.duration"
    />
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'

import { Badge } from '@/components/ui/badge'
import { Label } from '@/components/ui/label'
import { Slider } from '@/components/ui/slider'
import { useTracesStore } from '@/stores/traces'
import { getDurationRange } from '@/utils/traceFilter'

import ResetFilter from './ResetFilter.vue'

const tracesStore = useTracesStore()
const sliderRange = ref<number[]>([0, 0])

onMounted(() => {
  resetSliderBoundaries()
})

watch(
  () => tracesStore.datasetTraces.length,
  () => {
    resetSliderBoundaries()
  }
)

function resetSliderBoundaries() {
  const [minDuration, maxDuration] = getDurationRange(tracesStore.datasetTraces)

  sliderRange.value[0] = minDuration
  sliderRange.value[1] = maxDuration
}

function clearDurationFilter() {
  const min = sliderRange.value[0]
  const max = sliderRange.value[1]

  tracesStore.setTracesFilters({ duration: [min, max] })
}
</script>
