import { useMemo, useEffect, useImperativeHandle, forwardRef, useRef } from "react";
import { ChatFlowMessage } from "../../../hooks/useChatFlow";
import { ChatDateGroup } from "./ChatDateGroup";
import { ChatMessageItem } from "./ChatMessageItem";
import { ChatTypingIndicator } from "./ChatTypingIndicator";
import { extractDate } from "../../../utils/chatDateUtils";

interface ChatMessageListProps {
  messages: ChatFlowMessage[];
  onButtonClick: (buttonId: string, action: string) => void;
  isTyping: boolean;
  typingText: string;
}

interface MessageGroup {
  id: string;
  date: string;
  messages: ChatFlowMessage[];
}

export interface ChatMessageListRef {
  scrollToBottom: () => void;
}

export const ChatMessageList = forwardRef<ChatMessageListRef, ChatMessageListProps>(
  ({ messages, onButtonClick, isTyping, typingText }, ref) => {
    const messagesEndRef = useRef<HTMLDivElement>(null);

    const messageGroups = useMemo(() => {
      const groups: MessageGroup[] = [];

      for (const message of messages) {
        const dateStr = extractDate(message.datetime1, message.timestamp) || "";
        const lastGroup = groups[groups.length - 1];

        if (!lastGroup || lastGroup.date !== dateStr) {
          groups.push({
            id: `group-${groups.length}-${dateStr || "unknown"}`,
            date: dateStr,
            messages: [message],
          });
        } else {
          lastGroup.messages.push(message);
        }
      }

      return groups;
    }, [messages]);

    const scrollToBottom = () => {
      messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
    };

    useImperativeHandle(ref, () => ({
      scrollToBottom,
    }));

    useEffect(() => {
      scrollToBottom();
    }, [messages, isTyping, typingText]);

    return (
      <div className="space-y-4" dir="rtl">
        {messageGroups.map((group) => (
          <div key={group.id} className="space-y-4">
            <ChatDateGroup date={group.date} />

            {group.messages.map((message, index) => {
              const animationDelay = Math.min(index * 0.05, 1);

              return (
                <ChatMessageItem
                  key={message.id}
                  message={message}
                  animationDelay={animationDelay}
                  onButtonClick={onButtonClick}
                />
              );
            })}
          </div>
        ))}

        {/* Typing Indicator */}
        <ChatTypingIndicator isTyping={isTyping} typingText={typingText} />

        <div ref={messagesEndRef} />
      </div>
    );
  }
);

ChatMessageList.displayName = "ChatMessageList";
