import { ArrowDown } from 'lucide-react';
import { useVirtualizer } from '@tanstack/react-virtual';
import type { UseEmbeddableChatType } from '../EmbeddableChat/useEmbeddableChat';
import { MessageBubble, StreamingBubble } from './MessageBubble';

const OVERSCAN = 5;

type MessageListProps = {
  manager: UseEmbeddableChatType;
};

export const MessageList = ({ manager }: MessageListProps) => {
  const { messages, streamingText, isGenerating, showJumpToBottom, jumpToBottom, sendPrompt, scrollViewportRef, bottomRef } = manager;

  const virtualizer = useVirtualizer({
    count: messages.length,
    getScrollElement: () => scrollViewportRef.current,
    estimateSize: () => 150,
    overscan: OVERSCAN,
    measureElement: (element) => element.getBoundingClientRect().height,
  });

  return (
    <div className="flex-1 min-h-0 relative">
      <div ref={scrollViewportRef} className="h-full overflow-y-auto">
        {messages.length === 0 && !isGenerating && (
          <div className="flex items-center justify-center h-full min-h-[200px] text-duck-dark/30 text-sm">
            Send a message to start
          </div>
        )}
        {messages.length > 0 && (
          <div
            className="relative w-full"
            style={{ height: virtualizer.getTotalSize() }}
          >
            {virtualizer.getVirtualItems().map((virtualRow) => {
              const msg = messages[virtualRow.index]!;
              return (
                <div
                  key={virtualRow.key}
                  data-index={virtualRow.index}
                  ref={virtualizer.measureElement}
                  className="absolute top-0 left-0 w-full px-4"
                  style={{
                    transform: `translateY(${virtualRow.start}px)`,
                  }}
                >
                  <div className="py-1.5">
                    <MessageBubble message={msg} onAnswer={(text) => sendPrompt(text)} />
                  </div>
                </div>
              );
            })}
          </div>
        )}
        {isGenerating && (
          <div className="px-4 py-1.5">
            <StreamingBubble text={streamingText} />
          </div>
        )}
        <div ref={bottomRef} />
      </div>

      {showJumpToBottom && (
        <button
          onClick={jumpToBottom}
          className="absolute bottom-2 left-1/2 -translate-x-1/2 bg-duck-teal text-white rounded-full p-1.5 shadow-lg hover:bg-duck-teal/90 transition-colors cursor-pointer"
        >
          <ArrowDown className="h-4 w-4" />
        </button>
      )}
    </div>
  );
};
