<script lang="ts">
export interface MultiSelectOption {
  value: string
  label?: string
}
</script>

<script setup lang="ts">
import { computed, ref } from 'vue'
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'

const props = withDefaults(
  defineProps<{
    options: MultiSelectOption[]
    modelValue: string[]
    placeholder?: string
    searchPlaceholder?: string
    emptyText?: string
    maxHeight?: string
  }>(),
  {
    placeholder: 'Select items...',
    searchPlaceholder: 'Search...',
    emptyText: 'No items found',
    maxHeight: '300px',
  }
)

const emit = defineEmits<{
  'update:modelValue': [value: string[]]
}>()

const searchQuery = ref('')
const isOpen = ref(false)

const filteredOptions = computed(() => {
  if (!searchQuery.value) return props.options
  const query = searchQuery.value.toLowerCase()
  return props.options.filter(opt => {
    const label = opt.label || opt.value
    return label.toLowerCase().includes(query)
  })
})

const selectedLabels = computed(() => {
  return props.modelValue.map(val => {
    const opt = props.options.find(o => o.value === val)
    return opt?.label || val
  })
})

function toggleOption(value: string) {
  const newValue = [...props.modelValue]
  const idx = newValue.indexOf(value)
  if (idx >= 0) {
    newValue.splice(idx, 1)
  } else {
    newValue.push(value)
  }
  emit('update:modelValue', newValue)
}

function isSelected(value: string): boolean {
  return props.modelValue.includes(value)
}

function clearAll() {
  emit('update:modelValue', [])
}

function handleOpenChange(open: boolean) {
  isOpen.value = open
  if (!open) {
    searchQuery.value = ''
  }
}
</script>

<template>
  <DropdownMenu :open="isOpen" @update:open="handleOpenChange">
    <DropdownMenuTrigger as-child>
      <button
        type="button"
        class="flex w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
      >
        <span v-if="modelValue.length === 0" class="text-muted-foreground">
          {{ placeholder }}
        </span>
        <span v-else class="flex items-center gap-1 truncate">
          <span class="rounded bg-primary/10 px-1.5 py-0.5 text-xs font-medium text-primary">
            {{ modelValue.length }}
          </span>
          <span class="truncate text-muted-foreground">
            {{ selectedLabels.slice(0, 2).join(', ') }}{{ modelValue.length > 2 ? '...' : '' }}
          </span>
        </span>
        <i class="dku-icon-chevron-down-16 ml-2 shrink-0 opacity-50" />
      </button>
    </DropdownMenuTrigger>
    <DropdownMenuContent
      class="w-[--reka-dropdown-menu-trigger-width] p-0"
      align="start"
    >
      <!-- Search input -->
      <div class="flex items-center border-b px-3 py-2">
        <i class="dku-icon-search-16 mr-2 shrink-0 opacity-50" />
        <input
          v-model="searchQuery"
          type="text"
          :placeholder="searchPlaceholder"
          class="flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"
        />
        <Tooltip v-if="modelValue.length > 0">
          <TooltipTrigger as-child>
            <button
              type="button"
              class="ml-2 rounded p-0.5 text-muted-foreground hover:bg-accent hover:text-foreground"
              @click.stop="clearAll"
            >
              <i class="dku-icon-cancel-12" />
            </button>
          </TooltipTrigger>
          <TooltipContent>Clear all</TooltipContent>
        </Tooltip>
      </div>

      <!-- Options list -->
      <div
        class="overflow-y-auto p-1"
        :style="{ maxHeight }"
      >
        <div
          v-if="filteredOptions.length === 0"
          class="py-6 text-center text-sm text-muted-foreground"
        >
          {{ emptyText }}
        </div>
        <button
          v-for="option in filteredOptions"
          :key="option.value"
          type="button"
          class="relative flex w-full cursor-pointer select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground"
          @click.stop="toggleOption(option.value)"
        >
          <span class="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
            <i
              v-if="isSelected(option.value)"
              class="dku-icon-checkmark-16 text-primary"
            />
          </span>
          <span :class="{ 'font-medium': isSelected(option.value) }">
            {{ option.label || option.value }}
          </span>
        </button>
      </div>
    </DropdownMenuContent>
  </DropdownMenu>
</template>
