<script lang="ts" setup>
import type {DropdownMenuProps, EasyFlowDropdownMenuItem as IDropdownMenuItem,} from './interface';

import {computed, ref} from 'vue';

import {Search} from '@easyflow-core/icons';

import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuGroup,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
  Input,
} from '../../ui';

interface Props extends DropdownMenuProps {}

defineOptions({ name: 'DropdownMenu' });
const props = withDefaults(defineProps<Props>(), {
  align: 'start',
  searchEmptyText: '无匹配标签',
  searchPlaceholder: '搜索标签',
});

const searchKeyword = ref('');

const filteredMenus = computed(() => {
  const keyword = searchKeyword.value.trim().toLocaleLowerCase();
  if (!props.searchable || !keyword) {
    return props.menus;
  }
  return props.menus.filter((menu) =>
    menu.label.toLocaleLowerCase().includes(keyword),
  );
});

function handleItemClick(menu: IDropdownMenuItem) {
  if (menu.disabled) {
    return;
  }
  menu?.handler?.(props);
}
</script>
<template>
  <DropdownMenu>
    <DropdownMenuTrigger
      :aria-label="triggerLabel"
      class="flex h-full items-center gap-1"
    >
      <slot></slot>
    </DropdownMenuTrigger>
    <DropdownMenuContent :align="align" :class="contentClass">
      <div v-if="searchable" class="sticky top-0 z-10 bg-popover p-1">
        <div class="relative">
          <Search
            class="pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-[hsl(var(--text-muted))]"
          />
          <Input
            v-model="searchKeyword"
            :placeholder="searchPlaceholder"
            class="h-8 rounded-md border-[hsl(var(--line-subtle))] bg-[hsl(var(--surface-subtle))] py-1 pl-8 pr-2 text-xs"
            @keydown.stop
          />
        </div>
      </div>
      <DropdownMenuGroup>
        <template v-for="menu in filteredMenus" :key="menu.value">
          <DropdownMenuItem
            :disabled="menu.disabled"
            :class="{
              'bg-[hsl(var(--nav-item-active))] text-[hsl(var(--nav-item-active-foreground))] font-medium':
                menu.active,
            }"
            class="data-[state=checked]:bg-accent data-[state=checked]:text-accent-foreground text-foreground/80 mb-1 cursor-pointer"
            @click="handleItemClick(menu)"
          >
            <component :is="menu.icon" v-if="menu.icon" class="mr-2 size-4" />
            <span class="min-w-0 flex-1 truncate">
              {{ menu.label }}
            </span>
          </DropdownMenuItem>
          <DropdownMenuSeparator v-if="menu.separator" class="bg-border" />
        </template>
        <div
          v-if="filteredMenus.length === 0"
          class="px-3 py-5 text-center text-xs text-[hsl(var(--text-muted))]"
        >
          {{ searchEmptyText }}
        </div>
      </DropdownMenuGroup>
    </DropdownMenuContent>
  </DropdownMenu>
</template>
