"use client"; import { useState, useMemo } from "react"; import { Button } from "@/components/ui/button"; import { Badge } from "@/components/ui/badge"; import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, } from "@/components/ui/command"; import { Popover, PopoverContent, PopoverTrigger, } from "@/components/ui/popover"; import { CategoryIcon } from "@/components/ui/category-icon"; import { ChevronsUpDown, Check, X } from "lucide-react"; import { cn } from "@/lib/utils"; import type { Category } from "@/lib/types"; interface CategoryComboboxProps { categories: Category[]; value: string | null; onChange: (categoryId: string | null) => void; placeholder?: string; showBadge?: boolean; align?: "start" | "center" | "end"; width?: string; } export function CategoryCombobox({ categories, value, onChange, placeholder = "Sélectionner...", showBadge = false, align = "start", width = "w-[300px]", }: CategoryComboboxProps) { const [open, setOpen] = useState(false); // Organize categories by parent const { parentCategories, childrenByParent } = useMemo(() => { const parents = categories.filter((c) => c.parentId === null); const children: Record = {}; categories .filter((c) => c.parentId !== null) .forEach((child) => { if (!children[child.parentId!]) { children[child.parentId!] = []; } children[child.parentId!].push(child); }); return { parentCategories: parents, childrenByParent: children }; }, [categories]); const selectedCategory = categories.find((c) => c.id === value); const handleSelect = (categoryId: string | null) => { onChange(categoryId); setOpen(false); }; // Badge style trigger if (showBadge) { return ( e.preventDefault()} > Aucune catégorie trouvée. handleSelect(null)} > Aucune catégorie {parentCategories.map((parent) => (
handleSelect(parent.id)} > {parent.name} {childrenByParent[parent.id]?.map((child) => ( handleSelect(child.id)} className="pl-8" > {child.name} ))}
))}
); } // Button style trigger (default) return ( e.preventDefault()} > Aucune catégorie trouvée. {parentCategories.map((parent) => (
handleSelect(parent.id)} > {parent.name} {childrenByParent[parent.id]?.map((child) => ( handleSelect(child.id)} className="pl-8" > {child.name} ))}
))}
); }