"use client";

import { useEffect, useRef } from "react";
import { ChatMessage, ThreadState } from "@/lib/types";
import { Message } from "./Message";
import { TypingIndicator } from "./TypingIndicator";

interface MessageListProps {
  messages: ChatMessage[];
  isLoading: boolean;
  threads?: Map<string, ThreadState>;
  activeThreadId?: string | null;
  onOpenThread?: (threadId: string) => void;
  onSkipThread?: (threadId: string) => void;
  onDeleteThread?: (threadId: string, parentMessageId: string) => void;
}

export function MessageList({
  messages,
  isLoading,
  threads,
  activeThreadId,
  onOpenThread,
  onSkipThread,
  onDeleteThread,
}: MessageListProps) {
  const bottomRef = useRef<HTMLDivElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);

  // Auto-scroll to bottom
  useEffect(() => {
    if (bottomRef.current) {
      bottomRef.current.scrollIntoView({ behavior: "smooth" });
    }
  }, [messages, isLoading]);

  return (
    <div ref={containerRef} className="flex-1 overflow-y-auto min-h-0">
      {/* Top spacer */}
      <div className="h-4" />

      {/* Messages */}
      {messages.map((message) => {
        // Look up thread state if this message is a thread parent
        const threadState =
          message.threadId && threads
            ? threads.get(message.threadId) ?? undefined
            : undefined;
        const isActiveThread =
          message.threadId != null && message.threadId === activeThreadId;

        return (
          <Message
            key={message.id}
            message={message}
            threadState={threadState}
            isActiveThread={isActiveThread}
            onOpenThread={onOpenThread}
            onSkipThread={onSkipThread}
            onDeleteThread={onDeleteThread}
          />
        );
      })}

      {/* Typing indicator */}
      {isLoading && messages[messages.length - 1]?.content === "" && (
        <TypingIndicator />
      )}

      {/* Bottom anchor */}
      <div ref={bottomRef} className="h-4" />
    </div>
  );
}
