<script setup lang="ts">
import { useDark, watchDebounced } from '@vueuse/core'

import { Input } from '@/components/ui/input'
import { TooltipWrapper } from '@/components/ui/tooltip'
import { useUiStore } from '@/stores/uiStore'
import { GROUPS_CONFIG, GROUP_THEME_COLORS, type NodeGroupName } from '@/utils/nodeGroups'
import { WT1iser } from '@/services/wt1'

const uiStore = useUiStore()
const isDark = useDark()

const groups = Object.entries(GROUPS_CONFIG) as [
  NodeGroupName,
  (typeof GROUPS_CONFIG)[NodeGroupName],
][]

function getGroupBgColor(name: NodeGroupName) {
  const colors = GROUP_THEME_COLORS[name]
  return isDark.value ? colors.dark.bg : colors.light.bg
}

function getFilterButtonTitle(name: NodeGroupName) {
  if (uiStore.isGroupFilterActive(name)) {
    return `Remove ${name} filter`
  }
  return `Filter by ${name} nodes`
}

function handleGroupFilterClick(group: NodeGroupName) {
  uiStore.toggleGroupFilter(group)
  WT1iser.highlightNodes(group)
}

watchDebounced(
  () => uiStore.nodeSearchQuery,
  (query) => {
    if (query) WT1iser.searchNodes(query)
  },
  { debounce: 500 }
)
</script>

<template>
  <div class="space-y-3">
    <!-- Search Input -->
    <div class="relative">
      <i class="dku-icon-search-16 absolute left-2.5 top-2.5 text-muted-foreground/60" />
      <Input
        v-model="uiStore.nodeSearchQuery"
        placeholder="Search by name..."
        class="pl-9 h-9 w-full"
      />
    </div>

    <!-- Group Filter Buttons -->
    <div class="grid grid-cols-6 gap-1.5">
      <TooltipWrapper
        v-for="[name, config] in groups"
        :key="name"
        :content="getFilterButtonTitle(name)"
      >
        <button
          @click="handleGroupFilterClick(name)"
          :class="[
            'flex items-center justify-center gap-1.5 p-2 rounded-md text-xs font-medium border transition-all duration-150 hover:cursor-pointer',
            uiStore.isGroupFilterActive(name)
              ? 'border-current bg-current/10'
              : 'border-muted-foreground/30 text-muted-foreground/50 hover:border-muted-foreground/50',
          ]"
          :style="uiStore.isGroupFilterActive(name) ? { color: getGroupBgColor(name) } : {}"
        >
          <i :class="`${config.icon}-16`" />
        </button>
      </TooltipWrapper>
    </div>
  </div>
</template>
