import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Plus, MessageSquare, X, Package, ShoppingCart, MoreHorizontal, Edit, Trash2, Search } from "lucide-react";
import { cn } from "@/lib/utils";

interface Conversation {
  id: string;
  title: string;
  timestamp: string;
  type: 'general' | 'product' | 'order';
}

interface ChatSidebarProps {
  conversations: Conversation[];
  activeConversationId?: string;
  onConversationSelect: (id: string, e?: React.MouseEvent) => void;
  onNewConversation: (e?: React.MouseEvent) => void;
  onCloseSidebar?: () => void;
  onRenameConversation?: (id: string, newTitle: string) => void;
  onDeleteConversation?: (id: string) => void;
}

export function ChatSidebar({ 
  conversations, 
  activeConversationId, 
  onConversationSelect, 
  onNewConversation,
  onCloseSidebar,
  onRenameConversation,
  onDeleteConversation
}: ChatSidebarProps) {
  const [editingId, setEditingId] = useState<string | null>(null);
  const [editingTitle, setEditingTitle] = useState("");
  const [searchQuery, setSearchQuery] = useState("");

  const filteredConversations = searchQuery.trim()
    ? conversations.filter((c) =>
        c.title.toLowerCase().includes(searchQuery.trim().toLowerCase())
      )
    : conversations;

  const getConversationIcon = (type: Conversation['type']) => {
    switch (type) {
      case 'product':
        return <Package className="h-4 w-4" />;
      case 'order':
        return <ShoppingCart className="h-4 w-4" />;
      default:
        return <MessageSquare className="h-4 w-4" />;
    }
  };

  const handleRename = (id: string, currentTitle: string) => {
    setEditingId(id);
    setEditingTitle(currentTitle);
  };

  const handleConfirmRename = (id: string) => {
    if (editingTitle.trim() && onRenameConversation) {
      onRenameConversation(id, editingTitle.trim());
    }
    setEditingId(null);
    setEditingTitle("");
  };

  const handleCancelRename = () => {
    setEditingId(null);
    setEditingTitle("");
  };

  const handleDelete = (id: string) => {
    if (onDeleteConversation) {
      onDeleteConversation(id);
    }
  };

  return (
    <div className="flex h-full w-full flex-col border-r border-sidebar-border bg-sidebar">{/* 修改：w-80 改为 w-full */}
      {/* Header */}
      <div className="border-b border-sidebar-border p-4">
        <div className="flex items-center justify-end mb-4">
          <Button
            variant="ghost"
            size="icon"
            className="h-8 w-8 text-sidebar-foreground hover:bg-sidebar-accent"
            onClick={onCloseSidebar}
            title="关闭侧边栏"
          >
            <X className="h-4 w-4" />
          </Button>
        </div>
        
        <Button 
          onClick={(e) => {
            e.preventDefault();
            e.stopPropagation();
            onNewConversation(e);
          }}
          className="w-full bg-primary hover:bg-primary-hover text-primary-foreground shadow-md hover:shadow-lg transition-all duration-200 text-sm"
        >
          <Plus className="mr-1 h-4 w-4 flex-shrink-0" />
          <span className="truncate">新建对话</span>
        </Button>

        {/* 搜索框 */}
        {conversations.length > 3 && (
          <div className="relative mt-3">
            <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground pointer-events-none" />
            <Input
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              placeholder="搜索对话..."
              className="h-8 pl-8 text-xs bg-background/60 border-sidebar-border"
            />
          </div>
        )}
      </div>


      {/* Conversations List */}
      <ScrollArea className="flex-1">
        <div className="p-2">
          {filteredConversations.length === 0 ? (
            <div className="text-center text-muted-foreground py-8">
              <MessageSquare className="h-12 w-12 mx-auto mb-2 opacity-50" />
              <p>{searchQuery ? '没有匹配的对话' : '暂无对话记录'}</p>
              {!searchQuery && <p className="text-sm">开始您的第一次对话吧</p>}
            </div>
          ) : (
            <div className="space-y-1">
              {filteredConversations.map((conversation) => (
                <div
                  key={conversation.id}
                  className={cn(
                    "relative group rounded-lg transition-all duration-200",
                    "hover:bg-muted/30 hover:shadow-none",
                    activeConversationId === conversation.id
                      ? "bg-muted/50"
                      : ""
                  )}
                >
                  <button
                    onClick={(e) => {
                      e.preventDefault();
                      e.stopPropagation();
                      onConversationSelect(conversation.id, e);
                    }}
                    className={cn(
                      "w-full p-3 text-left transition-all duration-200",
                      activeConversationId === conversation.id
                        ? "text-foreground"
                        : "text-muted-foreground"
                    )}
                  >
                    <div className="flex items-start space-x-3">
                      <div className={cn(
                        "mt-0.5 transition-colors",
                        activeConversationId === conversation.id
                          ? "text-sidebar-primary-foreground"
                          : "text-muted-foreground group-hover:text-sidebar-foreground"
                      )}>
                        {getConversationIcon(conversation.type)}
                      </div>
                      <div className="flex-1 min-w-0 pr-8">
                        {editingId === conversation.id ? (
                          <Input
                            value={editingTitle}
                            onChange={(e) => setEditingTitle(e.target.value)}
                            onKeyDown={(e) => {
                              if (e.key === 'Enter') {
                                handleConfirmRename(conversation.id);
                              } else if (e.key === 'Escape') {
                                handleCancelRename();
                              }
                            }}
                            onBlur={() => handleConfirmRename(conversation.id)}
                            className="h-6 text-sm p-1 border-primary"
                            autoFocus
                            onClick={(e) => e.stopPropagation()}
                          />
                        ) : (
                          <>
                            <h3 className="font-medium truncate text-sm leading-5">
                              {conversation.title}
                            </h3>
                            <p className={cn(
                              "text-xs mt-1 truncate",
                              activeConversationId === conversation.id
                                ? "text-sidebar-primary-foreground/70"
                                : "text-muted-foreground"
                            )}>
                              {conversation.timestamp}
                            </p>
                          </>
                        )}
                      </div>
                    </div>
                  </button>
                  
                  {/* Action Menu */}
                  <div className="absolute right-2 top-2 opacity-0 group-hover:opacity-100 transition-opacity duration-200">
                    <DropdownMenu>
                      <DropdownMenuTrigger asChild>
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-6 w-6 text-muted-foreground hover:text-foreground hover:bg-muted/50"
                          onClick={(e) => e.stopPropagation()}
                        >
                          <MoreHorizontal className="h-3 w-3" />
                        </Button>
                      </DropdownMenuTrigger>
                      <DropdownMenuContent align="end" className="w-32">
                        <DropdownMenuItem
                          onClick={(e) => {
                            e.stopPropagation();
                            handleRename(conversation.id, conversation.title);
                          }}
                          className="cursor-pointer"
                        >
                          <Edit className="mr-2 h-3 w-3" />
                          重命名
                        </DropdownMenuItem>
                        <DropdownMenuItem
                          onClick={(e) => {
                            e.stopPropagation();
                            handleDelete(conversation.id);
                          }}
                          className="cursor-pointer text-destructive focus:text-destructive"
                        >
                          <Trash2 className="mr-2 h-3 w-3" />
                          删除
                        </DropdownMenuItem>
                      </DropdownMenuContent>
                    </DropdownMenu>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </ScrollArea>
    </div>
  );
}