import { useState, useEffect } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from "@/components/ui/alert-dialog";
import { 
  MessageSquare, 
  Calendar, 
  Trash2, 
  Eye,
  User,
  Bot,
  Clock,
  ChevronRight,
  Loader2
} from "lucide-react";
import { useToast } from "@/hooks/use-toast";
import { Checkbox } from "@/components/ui/checkbox";

interface Conversation {
  id: string;
  title: string;
  created_at: string;
  updated_at: string;
  messageCount: number;
  lastMessage: string;
}

interface Message {
  id: string;
  content: string;
  sender_type: string;
  message_type: string;
  created_at: string;
  metadata: any;
}

interface UserConversationsDialogProps {
  isOpen: boolean;
  onOpenChange: (open: boolean) => void;
  userId: string;
  userDisplayName: string;
  userAvatarUrl?: string;
}

export function UserConversationsDialog({ 
  isOpen, 
  onOpenChange, 
  userId, 
  userDisplayName,
  userAvatarUrl 
}: UserConversationsDialogProps) {
  const [conversations, setConversations] = useState<Conversation[]>([]);
  const [selectedConversation, setSelectedConversation] = useState<string | null>(null);
  const [messages, setMessages] = useState<Message[]>([]);
  const [loading, setLoading] = useState(false);
  const [messagesLoading, setMessagesLoading] = useState(false);
  const [selectedConversationIds, setSelectedConversationIds] = useState<string[]>([]);
  const { toast } = useToast();

  // 解析消息内容的辅助函数
  const parseMessageContent = (content: string) => {
    try {
      // 尝试解析JSON格式的消息内容
      const parsed = JSON.parse(content);
      if (typeof parsed === 'object' && parsed !== null) {
        // 如果是对象，提取其中的文本内容
        if (parsed.text) return parsed.text;
        if (parsed.content) return parsed.content;
        if (parsed.message) return parsed.message;
        // 如果没有明确的文本字段，返回JSON字符串（但格式化显示）
        return JSON.stringify(parsed, null, 2);
      }
      return content;
    } catch {
      // 如果不是JSON或解析失败，直接返回原内容
      return content;
    }
  };

  useEffect(() => {
    if (isOpen && userId) {
      fetchConversations();
    }
  }, [isOpen, userId]);

  const fetchConversations = async () => {
    setLoading(true);
    try {
      // 获取用户的对话列表
      const { data: conversationsData, error: conversationsError } = await supabase
        .from("conversations")
        .select("*")
        .eq("user_id", userId)
        .order("updated_at", { ascending: false });

      if (conversationsError) throw conversationsError;

      // 为每个对话获取消息统计和最后一条消息
      const conversationsWithStats = await Promise.all(
        (conversationsData || []).map(async (conversation) => {
          const { data: messagesData, error: messagesError } = await supabase
            .from("messages")
            .select("content, created_at")
            .eq("conversation_id", conversation.id)
            .order("created_at", { ascending: false })
            .limit(1);

          const { count } = await supabase
            .from("messages")
            .select("*", { count: "exact", head: true })
            .eq("conversation_id", conversation.id);

          return {
            ...conversation,
            messageCount: count || 0,
            lastMessage: messagesData?.[0]?.content ? 
              parseMessageContent(messagesData[0].content).slice(0, 50) + (parseMessageContent(messagesData[0].content).length > 50 ? '...' : '') : 
              "暂无消息",
          };
        })
      );

      setConversations(conversationsWithStats);
    } catch (error) {
      console.error("Error fetching conversations:", error);
      toast({
        title: "错误",
        description: "获取对话列表失败",
        variant: "destructive",
      });
    } finally {
      setLoading(false);
    }
  };

  const fetchMessages = async (conversationId: string) => {
    setMessagesLoading(true);
    try {
      const { data, error } = await supabase
        .from("messages")
        .select("*")
        .eq("conversation_id", conversationId)
        .order("created_at", { ascending: true });

      if (error) throw error;
      setMessages(data || []);
    } catch (error) {
      console.error("Error fetching messages:", error);
      toast({
        title: "错误",
        description: "获取消息失败",
        variant: "destructive",
      });
    } finally {
      setMessagesLoading(false);
    }
  };

  const deleteConversation = async (conversationId: string) => {
    try {
      // 先删除相关的消息
      const { error: messagesError } = await supabase
        .from("messages")
        .delete()
        .eq("conversation_id", conversationId);

      if (messagesError) throw messagesError;

      // 删除对话
      const { error: conversationError } = await supabase
        .from("conversations")
        .delete()
        .eq("id", conversationId);

      if (conversationError) throw conversationError;

      toast({
        title: "成功",
        description: "对话已删除",
      });

      // 重新获取对话列表
      fetchConversations();
      
      // 如果删除的是当前选中的对话，清空消息
      if (selectedConversation === conversationId) {
        setSelectedConversation(null);
        setMessages([]);
      }
    } catch (error) {
      console.error("Error deleting conversation:", error);
      toast({
        title: "错误",
        description: "删除对话失败",
        variant: "destructive",
      });
    }
  };

  const deleteSelectedConversations = async () => {
    try {
      // 批量删除消息
      const { error: messagesError } = await supabase
        .from("messages")
        .delete()
        .in("conversation_id", selectedConversationIds);

      if (messagesError) throw messagesError;

      // 批量删除对话
      const { error: conversationsError } = await supabase
        .from("conversations")
        .delete()
        .in("id", selectedConversationIds);

      if (conversationsError) throw conversationsError;

      toast({
        title: "成功",
        description: `已删除 ${selectedConversationIds.length} 个对话`,
      });

      // 清空选中状态
      setSelectedConversationIds([]);
      
      // 如果删除的包含当前选中的对话，清空消息
      if (selectedConversation && selectedConversationIds.includes(selectedConversation)) {
        setSelectedConversation(null);
        setMessages([]);
      }

      // 重新获取对话列表
      fetchConversations();
    } catch (error) {
      console.error("Error deleting conversations:", error);
      toast({
        title: "错误",
        description: "批量删除对话失败",
        variant: "destructive",
      });
    }
  };

  const toggleConversationSelection = (conversationId: string) => {
    setSelectedConversationIds(prev => 
      prev.includes(conversationId)
        ? prev.filter(id => id !== conversationId)
        : [...prev, conversationId]
    );
  };

  const toggleSelectAll = () => {
    if (selectedConversationIds.length === conversations.length) {
      setSelectedConversationIds([]);
    } else {
      setSelectedConversationIds(conversations.map(c => c.id));
    }
  };

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString("zh-CN", {
      year: "numeric",
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  };

  const getSenderIcon = (senderType: string) => {
    return senderType === "user" ? <User className="w-4 h-4" /> : <Bot className="w-4 h-4" />;
  };

  const getSenderLabel = (senderType: string) => {
    return senderType === "user" ? "用户" : "AI助手";
  };

  return (
    <Dialog open={isOpen} onOpenChange={onOpenChange}>
      <DialogContent className="max-w-7xl h-[85vh]">
        <DialogHeader className="pb-4">
          <DialogTitle className="flex items-center gap-3 text-xl">
            <Avatar className="h-10 w-10 ring-2 ring-primary/20">
              <AvatarImage src={userAvatarUrl || ""} />
              <AvatarFallback className="bg-primary/10 text-primary font-semibold">
                {userDisplayName?.charAt(0) || "U"}
              </AvatarFallback>
            </Avatar>
            <div className="flex flex-col items-start">
              <span className="font-bold">{userDisplayName}</span>
              <span className="text-sm font-normal text-muted-foreground">的对话记录管理</span>
            </div>
          </DialogTitle>
          <DialogDescription className="sr-only">
            查看和管理用户的所有对话记录，包括对话列表和详细消息内容
          </DialogDescription>
        </DialogHeader>

        <div className="flex gap-6 h-[600px]">
          {/* 左侧对话列表 */}
          <div className="w-1/3 min-w-[320px]">
            <div className="flex items-center justify-between mb-6">
              <div className="flex items-center gap-3">
                {conversations.length > 0 && (
                  <Checkbox
                    checked={selectedConversationIds.length === conversations.length}
                    onCheckedChange={toggleSelectAll}
                  />
                )}
                <h3 className="text-lg font-semibold flex items-center gap-2">
                  <div className="p-2 rounded-lg bg-primary/10">
                    <MessageSquare className="w-5 h-5 text-primary" />
                  </div>
                  对话列表
                  <Badge variant="outline" className="ml-2 font-medium">
                    {conversations.length}
                  </Badge>
                </h3>
              </div>
              {selectedConversationIds.length > 0 && (
                <AlertDialog>
                  <AlertDialogTrigger asChild>
                    <Button
                      variant="destructive"
                      size="sm"
                      className="gap-2"
                    >
                      <Trash2 className="w-4 h-4" />
                      删除选中 ({selectedConversationIds.length})
                    </Button>
                  </AlertDialogTrigger>
                  <AlertDialogContent>
                    <AlertDialogHeader>
                      <AlertDialogTitle>确认批量删除对话</AlertDialogTitle>
                      <AlertDialogDescription>
                        您确定要删除选中的 {selectedConversationIds.length} 个对话吗？此操作不可撤销，将同时删除这些对话中的所有消息。
                      </AlertDialogDescription>
                    </AlertDialogHeader>
                    <AlertDialogFooter>
                      <AlertDialogCancel>取消</AlertDialogCancel>
                      <AlertDialogAction
                        onClick={deleteSelectedConversations}
                        className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                      >
                        删除
                      </AlertDialogAction>
                    </AlertDialogFooter>
                  </AlertDialogContent>
                </AlertDialog>
              )}
            </div>

            {loading ? (
              <div className="flex flex-col items-center justify-center h-32 space-y-3">
                <Loader2 className="w-8 h-8 animate-spin text-primary" />
                <span className="text-sm text-muted-foreground">加载对话列表...</span>
              </div>
            ) : conversations.length > 0 ? (
              <ScrollArea className="h-[520px] pr-2">
                <div className="space-y-3">
                  {conversations.map((conversation) => (
                    <Card
                      key={conversation.id}
                      className={`transition-all duration-300 hover:shadow-lg hover:-translate-y-0.5 ${
                        selectedConversation === conversation.id 
                          ? "border-primary bg-gradient-to-r from-primary/10 to-primary/5 shadow-md ring-1 ring-primary/20" 
                          : "hover:bg-accent/30 border-border/50"
                      }`}
                    >
                      <CardContent className="p-4">
                        <div className="space-y-3">
                          <div className="flex items-start justify-between">
                            <div className="flex items-start gap-3 flex-1 cursor-pointer" onClick={() => {
                              setSelectedConversation(conversation.id);
                              fetchMessages(conversation.id);
                            }}>
                              <Checkbox
                                checked={selectedConversationIds.includes(conversation.id)}
                                onCheckedChange={() => toggleConversationSelection(conversation.id)}
                                onClick={(e) => e.stopPropagation()}
                                className="mt-1"
                              />
                              <div className="flex-1">
                                <h4 className="font-semibold text-sm leading-tight pr-3 line-clamp-2">
                                  {conversation.title}
                                </h4>
                              </div>
                            </div>
                            <div className="flex items-center gap-2 shrink-0">
                              <Badge 
                                variant={selectedConversation === conversation.id ? "default" : "secondary"}
                                className="text-xs font-medium"
                              >
                                {conversation.messageCount}条
                              </Badge>
                              {selectedConversation === conversation.id && (
                                <ChevronRight className="w-4 h-4 text-primary animate-pulse" />
                              )}
                            </div>
                          </div>
                          
                          <p className="text-xs text-muted-foreground line-clamp-2 leading-relaxed bg-muted/30 rounded p-2">
                            {conversation.lastMessage}
                          </p>
                          
                          <div className="flex items-center justify-between pt-2 border-t border-border/30">
                            <span className="flex items-center gap-1.5 text-xs text-muted-foreground">
                              <Clock className="w-3.5 h-3.5" />
                              {new Date(conversation.created_at).toLocaleDateString('zh-CN', {
                                month: 'numeric',
                                day: 'numeric',
                                hour: 'numeric',
                                minute: 'numeric'
                              })}
                            </span>
                            <AlertDialog>
                              <AlertDialogTrigger asChild>
                                <Button
                                  variant="ghost"
                                  size="sm"
                                  className="h-6 w-6 p-0 text-destructive/60 hover:text-destructive hover:bg-destructive/10"
                                  onClick={(e) => e.stopPropagation()}
                                >
                                  <Trash2 className="w-3.5 h-3.5" />
                                </Button>
                              </AlertDialogTrigger>
                              <AlertDialogContent>
                                <AlertDialogHeader>
                                  <AlertDialogTitle>确认删除对话</AlertDialogTitle>
                                  <AlertDialogDescription>
                                    您确定要删除对话 "{conversation.title}" 吗？此操作不可撤销，将同时删除该对话中的所有消息。
                                  </AlertDialogDescription>
                                </AlertDialogHeader>
                                <AlertDialogFooter>
                                  <AlertDialogCancel>取消</AlertDialogCancel>
                                  <AlertDialogAction
                                    onClick={() => deleteConversation(conversation.id)}
                                    className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                                  >
                                    删除
                                  </AlertDialogAction>
                                </AlertDialogFooter>
                              </AlertDialogContent>
                            </AlertDialog>
                          </div>
                        </div>
                      </CardContent>
                    </Card>
                  ))}
                </div>
              </ScrollArea>
            ) : (
              <div className="flex flex-col items-center justify-center h-64 text-muted-foreground space-y-4">
                <div className="p-4 rounded-full bg-muted/30">
                  <MessageSquare className="w-12 h-12 opacity-50" />
                </div>
                <div className="text-center space-y-1">
                  <p className="font-medium">暂无对话记录</p>
                  <p className="text-xs">该用户还没有开始任何对话</p>
                </div>
              </div>
            )}
          </div>

          {/* 右侧消息详情 */}
          <div className="flex-1 border-l pl-6">
            {selectedConversation ? (
              <div className="h-full flex flex-col">
                <div className="border-b pb-4 mb-6">
                  <h3 className="text-lg font-semibold flex items-center gap-2">
                    <div className="p-2 rounded-lg bg-blue-500/10">
                      <Eye className="w-5 h-5 text-blue-500" />
                    </div>
                    对话详情
                  </h3>
                  <p className="text-sm text-muted-foreground mt-2 bg-muted/30 rounded p-2">
                    {conversations.find(c => c.id === selectedConversation)?.title}
                  </p>
                </div>

                <ScrollArea className="flex-1 pr-2">
                  {messagesLoading ? (
                    <div className="flex flex-col items-center justify-center py-12 space-y-3">
                      <Loader2 className="w-8 h-8 animate-spin text-primary" />
                      <span className="text-sm text-muted-foreground">加载消息内容...</span>
                    </div>
                  ) : messages.length === 0 ? (
                    <div className="flex flex-col items-center justify-center py-12 text-muted-foreground space-y-4">
                      <div className="p-4 rounded-full bg-muted/30">
                        <MessageSquare className="w-10 h-10 opacity-50" />
                      </div>
                      <div className="text-center space-y-1">
                        <p className="font-medium">该对话暂无消息</p>
                        <p className="text-xs">还没有任何消息记录</p>
                      </div>
                    </div>
                  ) : (
                    <div className="space-y-6">
                      {messages.map((message, index) => (
                        <div key={message.id} className="group">
                          <div className={`flex items-start gap-4 ${
                            message.sender_type === "user" ? "flex-row-reverse" : ""
                          }`}>
                            <div className="flex-shrink-0 order-1">
                              <div className={`p-2 rounded-full ${
                                message.sender_type === "user" 
                                  ? "bg-blue-500/10" 
                                  : "bg-primary/10"
                              }`}>
                                {getSenderIcon(message.sender_type)}
                              </div>
                            </div>
                            
                            <div className={`flex-1 order-2 ${
                              message.sender_type === "user" ? "text-right" : ""
                            }`}>
                              <div className="flex items-center gap-2 mb-2">
                                <Badge 
                                  variant={message.sender_type === "user" ? "outline" : "default"}
                                  className="text-xs font-medium"
                                >
                                  {getSenderLabel(message.sender_type)}
                                </Badge>
                                <Badge variant="secondary" className="text-xs">
                                  {message.message_type}
                                </Badge>
                              </div>
                              
                              <div className={`rounded-xl p-4 max-w-[85%] ${
                                message.sender_type === "user"
                                  ? "bg-blue-50 border border-blue-200 ml-auto"
                                  : "bg-muted/50 border border-border/50"
                              }`}>
                                <div className="whitespace-pre-wrap break-words text-sm leading-relaxed">
                                  {parseMessageContent(message.content)}
                                </div>
                              </div>
                              
                              <div className={`flex items-center gap-2 mt-2 text-xs text-muted-foreground ${
                                message.sender_type === "user" ? "justify-end" : ""
                              }`}>
                                <Clock className="w-3 h-3" />
                                {formatDate(message.created_at)}
                              </div>
                            </div>
                          </div>
                          
                          {index < messages.length - 1 && (
                            <div className="my-6 flex items-center">
                              <div className="flex-1 border-t border-border/30"></div>
                              <div className="px-4 text-xs text-muted-foreground bg-background">
                                • • •
                              </div>
                              <div className="flex-1 border-t border-border/30"></div>
                            </div>
                          )}
                        </div>
                      ))}
                    </div>
                  )}
                </ScrollArea>
              </div>
            ) : (
              <div className="flex items-center justify-center h-full text-muted-foreground">
                <div className="text-center space-y-4">
                  <div className="p-6 rounded-full bg-muted/30 mx-auto w-fit">
                    <MessageSquare className="w-16 h-16 opacity-30" />
                  </div>
                  <div className="space-y-2">
                    <p className="text-lg font-medium">选择对话查看详情</p>
                    <p className="text-sm opacity-70">从左侧列表选择一个对话来查看完整的消息历史</p>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}