import { useRef } from "react";
import { useVirtualizer } from "@tanstack/react-virtual";
import Conversation from "../sidebar/Conversation";
import { Conversation as ConversationType } from "../../types/type";

interface Props {
  conversations: ConversationType[];
  /**
   * Bounds the scroll container when the list sits inside a collapsible
   * service group. Omit to fill the parent, which must itself be bounded —
   * the virtualizer measures this element and renders nothing if it has no
   * definite height.
   */
  bounded?: boolean;
}

/** Matches the 56px spec row plus its 4px separation. */
const ITEM_HEIGHT = 60;

const VirtualizedChatList = ({ conversations, bounded }: Props) => {
  const parentRef = useRef<HTMLDivElement>(null);

  const virtualizer = useVirtualizer({
    count: conversations.length,
    getScrollElement: () => parentRef.current,
    estimateSize: () => ITEM_HEIGHT,
    overscan: 5,
  });

  return (
    <div
      ref={parentRef}
      className={`chat-vlist${bounded ? " chat-vlist--bounded" : ""}`}
    >
      <div
        className="chat-vlist__sizer"
        style={{ height: `${virtualizer.getTotalSize()}px` }}
      >
        {virtualizer.getVirtualItems().map((item) => {
          const conversation = conversations[item.index];
          return (
            <div
              key={item.key}
              className="chat-vlist__item"
              style={{
                height: `${item.size}px`,
                transform: `translateY(${item.start}px)`,
              }}
            >
              <Conversation
                conversation={conversation}
                lastIdx={item.index === conversations.length - 1}
              />
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default VirtualizedChatList;
