import { useState, useRef, useEffect } from "react"; import { Text } from "./Text"; interface Option { value: string | number; label: string; } interface MultiSelectProps { name?: string; label?: string; options: Option[]; value: (string | number)[]; onChange: (values: (string | number)[]) => void; placeholder?: string; error?: string; required?: boolean; disabled?: boolean; className?: string; } export function MultiSelect({ name, label, options, value, onChange, placeholder = "اختر العناصر...", error, required, disabled, className = "" }: MultiSelectProps) { const [isOpen, setIsOpen] = useState(false); const containerRef = useRef(null); // Close dropdown when clicking outside useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if (containerRef.current && !containerRef.current.contains(event.target as Node)) { setIsOpen(false); } }; document.addEventListener("mousedown", handleClickOutside); return () => document.removeEventListener("mousedown", handleClickOutside); }, []); const handleToggleOption = (optionValue: string | number) => { if (disabled) return; const newValue = value.includes(optionValue) ? value.filter(v => v !== optionValue) : [...value, optionValue]; onChange(newValue); }; const handleRemoveItem = (optionValue: string | number) => { if (disabled) return; onChange(value.filter(v => v !== optionValue)); }; const selectedOptions = options.filter(option => value.includes(option.value)); const displayText = selectedOptions.length > 0 ? `تم اختيار ${selectedOptions.length} عنصر` : placeholder; return (
{label && ( )} {/* Hidden input for form submission */} {name && ( )} {/* Selected items display */} {selectedOptions.length > 0 && (
{selectedOptions.map((option) => ( {option.label} {!disabled && ( )} ))}
)} {/* Dropdown trigger */}
!disabled && setIsOpen(!isOpen)} >
0 ? 'text-gray-900' : 'text-gray-500'}> {displayText}
{/* Dropdown menu */} {isOpen && (
{options.length === 0 ? (
لا توجد خيارات متاحة
) : ( options.map((option) => { const isSelected = value.includes(option.value); return (
handleToggleOption(option.value)} > {option.label} {isSelected && ( )}
); }) )}
)} {error && ( {error} )}
); }