"use client" import * as React from "react" import { X } from "lucide-react" import { Badge } from "@/components/ui/badge" import { Command, CommandGroup, CommandItem } from "@/components/ui/command" import { Command as CommandPrimitive } from "cmdk" interface MultiSelectProps { options: { label: string; value: string }[] selected: string[] onChange: (selected: string[]) => void placeholder?: string } export function MultiSelect({ options, selected, onChange, placeholder = "Select options" }: MultiSelectProps) { const inputRef = React.useRef(null) const [open, setOpen] = React.useState(false) const [inputValue, setInputValue] = React.useState("") const handleUnselect = (value: string) => { onChange(selected.filter((s) => s !== value)) } const handleSelect = (value: string) => { if (selected.includes(value)) { onChange(selected.filter((s) => s !== value)) } else { onChange([...selected, value]) } } const handleKeyDown = (e: React.KeyboardEvent) => { const input = inputRef.current if (input) { if (e.key === "Delete" || e.key === "Backspace") { if (input.value === "" && selected.length > 0) { onChange(selected.slice(0, -1)) } } if (e.key === "Escape") { input.blur() } } } const selectedOptions = options.filter((option) => selected.includes(option.value)) return (
{selectedOptions.map((option) => ( {option.label} ))} setOpen(false)} onFocus={() => setOpen(true)} placeholder={selected.length === 0 ? placeholder : undefined} className="ml-2 flex-1 bg-transparent outline-none placeholder:text-muted-foreground" />
{open && options.length > 0 && (
{options.map((option) => { const isSelected = selected.includes(option.value) return ( { e.preventDefault() e.stopPropagation() }} onSelect={() => handleSelect(option.value)} className={`flex items-center gap-2 ${isSelected ? "bg-muted" : ""}`} >
{option.label}
) })}
)}
) }