<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 PasteNewTrace from './PasteNewTrace.vue'
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 { Separator } from '@/components/ui/separator'
import { Slider } from '@/components/ui/slider'
import { useFormatters } from '@/composables/useFormatters'
import { useReloadTraces } from '@/composables/useTraces'
import { TooltipWrapper } from '@/components/ui/tooltip'
import { useUiStore } from '@/stores/uiStore'
import { useTracesStore } from '@/stores/tracesStore'
import { WT1iser } from '@/services/wt1'

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

function handleReload() {
  reloadTraces(undefined, {
    onSuccess: () => {
      WT1iser.reloadTraces()
      toast.success('Dataset 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 class="flex-1 overflow-y-auto">
    <!-- Traces actions -->
    <div class="p-4 gap-2 flex flex-col">
      <TooltipWrapper content="Paste a new local trace">
        <PasteNewTrace>
          <Button class="w-full">
            <i class="dku-icon-plus-16" />
            Paste a new trace
          </Button>
        </PasteNewTrace>
      </TooltipWrapper>

      <Button variant="secondary" class="w-full" :disabled="isReloading" @click="handleReload">
        <i class="dku-icon-arrow-clockwise-16" :class="isReloading && 'animate-spin'" />
        {{ isReloading ? 'Reloading...' : 'Reload traces' }}
      </Button>
    </div>

    <Separator />

    <div v-if="tracesStores.hasApiTraces">
      <!-- Filters Header -->
      <div class="flex justify-between items-center bg-sidebar-accent px-4 py-2">
        <div class="font-medium">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>
  </div>
</template>
