
import React, { useRef, useEffect } from "react";
import { format } from "date-fns";
import { MessageSquare, Loader2 } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { Separator } from "@/components/ui/separator";

interface ConversationHistoryProps {
  conversations: Conversation[];
  isLoading: boolean;
  refreshData: () => void;
  userId: string; 
}


export function ConversationHistory({ 
  conversations, 
  isLoading, 
  refreshData,
  userId
}: ConversationHistoryProps) {
  const chatContainerRef = useRef<HTMLDivElement>(null);

  // Add auto-refresh effect
  useEffect(() => {
    // Set up an interval to refresh data every 3 seconds
    const intervalId = setInterval(() => {
      refreshData();
    }, 3000);
    
    // Clean up the interval when component unmounts
    return () => clearInterval(intervalId);
  }, [refreshData]);

  useEffect(() => {
    if (chatContainerRef.current && conversations.length > 0) {
      chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
    }
    
    // Mark messages as read when component mounts or conversations change
    const markMessagesAsRead = async () => {
      if (conversations.length > 0) {
        try {
          // Mark all messages in the first conversation as read
          await fetch(`/api/users/${userId}/conversations/${conversations[0].id}/read`, {
            method: "POST",
          });
        } catch (error) {
          console.error("Error marking messages as read:", error);
        }
      }
    };
    
    markMessagesAsRead();
  }, [conversations, userId]);


  useEffect(() => {
    if (chatContainerRef.current && conversations.length > 0) {
      chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
    }
  }, [conversations]);

  if (isLoading) {
    return (
      <div className="flex justify-center items-center py-12">
        <Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (conversations.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center py-12 text-center">
        <MessageSquare className="h-16 w-16 opacity-20 mb-4" />
        <h3 className="text-lg font-medium mb-2">هیچ مکالمه‌ای یافت نشد</h3>
        <p className="text-muted-foreground">این کاربر هنوز مکالمه‌ای انجام نداده است.</p>
      </div>
    );
  }

  return (
    <div ref={chatContainerRef} className="space-y-8 overflow-auto max-h-[700px] pr-2">
      {conversations.map((conversation, idx) => (
        <div key={conversation.id}>
          {/* اطلاعات مکالمه */}
          <div className="flex justify-between items-start mb-4">
            <div>
              <h3 className="text-lg font-medium">
                {conversation.title || "مکالمه بدون عنوان"}
              </h3>
              <div className="flex items-center text-sm text-muted-foreground mt-1">
                <span className="ml-4">
                  تاریخ: {format(new Date(conversation.createdAt), "yyyy/MM/dd")}
                </span>
                <span>
                  شناسه چت: {conversation.telegramChatId}
                </span>
              </div>
            </div>
          </div>

          {/* بخش پیام‌ها */}
          <div className="space-y-4 mb-6">
            {conversation.messages && conversation.messages.length > 0 ? (
              conversation.messages.map((message, index) => (
                <div
                  key={message.id || index}
                  className={`p-4 rounded-lg ${message.role === "user"
                    ? "bg-blue-900 text-white mr-auto"
                    : "bg-gray-800 text-white ml-auto"
                    } max-w-[80%]`}
                >
                  <div className="mb-2">
                    <Badge variant="outline" className="mb-2">
                      {message.role === "user" ? "کاربر" : "سیستم"}
                    </Badge>
                  </div>
                  <p className="whitespace-pre-wrap">{message.content}</p>
                  <div className="mt-2 text-xs text-gray-500 text-left">
                    {format(new Date(message.createdAt), "HH:mm")}
                  </div>
                </div>
              ))
            ) : (
              <div className="text-center text-muted-foreground p-4 bg-muted/20 rounded">
                هیچ پیامی در این مکالمه وجود ندارد
              </div>
            )}
          </div>

          {/* خط جداکننده بین مکالمات، به جز آخرین مکالمه */}
          {idx < conversations.length - 1 && (
            <Separator className="my-8" />
          )}
        </div>
      ))}
    </div>
  );
}