import { CheckIcon, EditIcon, HistoryIcon, PlusIcon, TrashIcon, XIcon } from 'lucide-react' import { useState } from 'react' import { Button, cn, Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator, Input, Popover, PopoverContent, PopoverTrigger, ScrollArea, } from 'ui' import { ShortcutTooltip } from '../ShortcutTooltip' import { useAiAssistantStateSnapshot } from '@/state/ai-assistant-state' import { SHORTCUT_IDS } from '@/state/shortcuts/registry' import { useShortcut } from '@/state/shortcuts/useShortcut' interface AIAssistantChatSelectorProps { disabled?: boolean shortcutsEnabled?: boolean } export const AIAssistantChatSelector = ({ disabled = false, shortcutsEnabled = true, }: AIAssistantChatSelectorProps) => { const snap = useAiAssistantStateSnapshot() const [chatSelectorOpen, setChatSelectorOpen] = useState(false) const [editingChatId, setEditingChatId] = useState(null) const [editingChatName, setEditingChatName] = useState('') const chats = Object.entries(snap.chats) useShortcut( SHORTCUT_IDS.AI_ASSISTANT_TOGGLE_HISTORY, () => setChatSelectorOpen((prev) => !prev), { enabled: shortcutsEnabled, } ) const handleSelectChat = (id: string) => { snap.selectChat(id) setChatSelectorOpen(false) } const handleDeleteChat = (id: string, e?: React.MouseEvent) => { if (e) e.stopPropagation() snap.deleteChat(id) } const handleStartEditChat = (id: string, name: string, e?: React.MouseEvent) => { if (e) e.stopPropagation() setEditingChatId(id) setEditingChatName(name) } const handleSaveEditChat = (e?: React.MouseEvent) => { if (e) e.stopPropagation() if (editingChatId && editingChatName.trim()) { snap.renameChat(editingChatId, editingChatName.trim()) setEditingChatId(null) setEditingChatName('') } } const handleCancelEditChat = (e?: React.MouseEvent | React.FocusEvent) => { if (e) e.stopPropagation() setEditingChatId(null) setEditingChatName('') } const handleInputBlur = (e: React.FocusEvent) => { e.stopPropagation() const relatedTarget = e.relatedTarget as HTMLElement | null const isSaveOrCancelButton = relatedTarget?.closest('button') if (!isSaveOrCancelButton && editingChatId && editingChatName.trim()) { handleSaveEditChat() } else if (!isSaveOrCancelButton) { handleCancelEditChat(e) } } return (