<script setup lang="ts">
import { getLocalTimeZone } from '@internationalized/date'
import { watchDebounced } from '@vueuse/core'
import { storeToRefs } from 'pinia'
import { computed } from 'vue'
import { toast } from 'vue-sonner'

import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
import { RangeCalendar } from '@/components/ui/range-calendar'
import { useSidebar } from '@/components/ui/sidebar'
import { Slider } from '@/components/ui/slider'
import { useFormatters } from '@/composables/useFormatters'
import { useReloadTraces } from '@/composables/useTraces'
import { useUiStore } from '@/stores/uiStore'
import { useTracesStore } from '@/stores/tracesStore'
import { WT1iser } from '@/services/wt1'

const uiStore = useUiStore()
const tracesStores = useTracesStore()
const { open } = useSidebar()
const { mutate: reloadTraces, isPending: isReloading } = useReloadTraces()

function handleReload() {
  reloadTraces(undefined, {
    onSuccess: () => {
      WT1iser.reloadTraces()
      toast.success('Traces reloaded')
    },
    onError: (err: Error) => {
      toast.error('Failed to reload traces', {
        description: err.message || 'An unexpected error occurred',
      })
    },
  })
}

watchDebounced(
  () => [
    uiStore.nameSearchQuery,
    uiStore.resultSearchQuery,
    uiStore.durationRange,
    uiStore.dateRange,
  ],
  () => {
    WT1iser.filterTraces(
      uiStore.nameSearchQuery,
      uiStore.durationRange?.join('-') ?? '',
      uiStore.dateRange?.start?.toString() ?? '',
      uiStore.dateRange?.end?.toString() ?? '',
    )
  },
  { debounce: 500 },
)
const { durationRange, durationMax, dateRange } = storeToRefs(uiStore)

const { simpleDateFormatter, formatMillis } = useFormatters()

const formattedDateRange = computed(() => {
  if (!dateRange.value?.start) return 'Pick a date range'

  const start = dateRange.value.start.toDate(getLocalTimeZone())
  const end = dateRange.value.end?.toDate(getLocalTimeZone())

  if (!end) return simpleDateFormatter.format(start)

  return `${simpleDateFormatter.format(start)} - ${simpleDateFormatter.format(end)}`
})

const sliderDurationRange = computed({
  get: () => durationRange.value ?? [0, durationMax.value],
  set: (val) => {
    durationRange.value = val as [number, number]
  },
})

const formattedDuration = computed(() => {
  const [min, max] = sliderDurationRange.value
  return `${formatMillis(min)} - ${formatMillis(max)}`
})

const formattedDurationMax = computed(() => formatMillis(durationMax.value))
</script>

<template>
  <div v-if="tracesStores.hasApiTraces && open" class="border-t">
    <!-- Filters Header -->
    <div class="flex justify-between items-center bg-sidebar-accent px-4 py-2">
      <div class="font-medium text-sm">Filters</div>
      <Button variant="link" class="p-2 border-none" size="sm" @click="uiStore.clearTraceFilters">
        Clear
      </Button>
    </div>

    <div class="p-4 flex flex-col gap-4">
      <!-- Date Range -->
      <div class="space-y-2">
        <Label class="font-medium text-foreground">Date range</Label>
        <Popover>
          <PopoverTrigger as-child>
            <Button
              variant="outline"
              class="w-full justify-start text-left font-normal h-9 normal-case"
              :class="!dateRange?.start && 'text-muted-foreground'"
            >
              <i class="dku-icon-calendar-16 mr-2 opacity-50" />
              <span class="truncate">
                {{ formattedDateRange }}
              </span>
            </Button>
          </PopoverTrigger>
          <PopoverContent
            class="w-auto p-0 bg-background/95 backdrop-blur-xl border-border/60 shadow-xl"
            align="start"
          >
            <RangeCalendar v-model="dateRange" />
          </PopoverContent>
        </Popover>
      </div>

      <!-- Duration -->
      <div class="space-y-3">
        <div class="flex items-center justify-between">
          <Label class="font-medium text-foreground">Duration</Label>
          <span class="text-xs font-mono text-muted-foreground">{{ formattedDuration }}</span>
        </div>
        <Slider
          v-model="sliderDurationRange"
          :max="durationMax"
          :step="100"
          :min="0"
          :min-steps-between-thumbs="1"
          class="[&_.absolute]:bg-primary/80"
        />
        <div class="flex justify-between text-xs text-muted-foreground/50 font-mono px-1">
          <span>0ms</span>
          <span>{{ formattedDurationMax }}</span>
        </div>
      </div>
    </div>
  </div>
</template>
