import React, { useRef } from "react";
import { ReactComponent as CommentIndicator } from "../../assets/comment-indicator.svg";

export const withCommentIcon = (Renderer) => {
  return (props) => {
    const iconRef = useRef(null);

    const {
      handleCommentIconHover,
      handleMouseEnter,
      handleMouseLeave,
      popup,
      resolvedComments,
      getLatestUnresolvedThreadId,
      configuration,
      colIdentifierKey,
    } = props.context;
    // Use colIdentifierKey if provided, otherwise fallback to props.node.id
    const rowIdentifier = colIdentifierKey
      ? props.data?.[colIdentifierKey] || props.node.id
      : props.node.id;
    const baseCellId = `${rowIdentifier}__${props.column.getColId()}`;
    // If base is resolved, prefer latest unresolved thread; otherwise create a new thread
    let effectiveCellId = baseCellId;
    if (
      popup?.cellId != baseCellId &&
      !configuration?.disableMultiCommentThread
    ) {
      const baseResolved = Array.isArray(resolvedComments)
        ? resolvedComments.includes(baseCellId)
        : false;
      if (baseResolved) {
        const latestUnresolved = getLatestUnresolvedThreadId(baseCellId);
        if (latestUnresolved) {
          effectiveCellId = latestUnresolved;
        } else {
          effectiveCellId = baseCellId;
        }
        // effectiveCellId = latestUnresolved || getEffectiveCellId(baseCellId);
      }
    }

    // const cellId = `${props.node.id}__${props.column.getColId()}`;
    const commentsArray = props.context.comments?.[effectiveCellId];
    const hasComment =
      commentsArray && Array.isArray(commentsArray) && commentsArray.length > 0;

    const isPortalOpen = popup?.cellId === effectiveCellId;

    // Render consumer-provided renderer or the (formatted) value
    // Prefer AG Grid's valueFormatter output when provided
    const displayValue =
      props.valueFormatted !== undefined && props.valueFormatted !== null
        ? props.valueFormatted
        : props.value;
    // Ensure non-renderable objects are stringified to avoid React child errors
    const safeValue =
      displayValue !== null && typeof displayValue === "object"
        ? JSON.stringify(displayValue)
        : displayValue ?? "";
    const Content = Renderer ? <Renderer {...props} /> : <>{safeValue}</>;
    const isResolved =
      Array.isArray(resolvedComments) &&
      resolvedComments.find((comment) => comment === effectiveCellId);
    return (
      <>
        <div
          style={{
            position: "absolute",
            top: 0,
            left: 0,
            right: 0,
            bottom: 0,
            border: hasComment && isPortalOpen ? "1px solid #4259ee" : "none",
            boxSizing: "border-box",
            pointerEvents: "none",
            zIndex: 1,
          }}
        />
        {Content}
        {hasComment && !isResolved && (
          <div
            ref={iconRef}
            onMouseOver={() => {
              handleMouseEnter();
              handleCommentIconHover(props);
            }}
            onMouseLeave={handleMouseLeave}
            title={`${commentsArray.length} comment${
              commentsArray.length > 1 ? "s" : ""
            }`}
            style={{
              position: "absolute",
              top: -15,
              right: 0,
              cursor: "pointer",
              zIndex: 2,
            }}
          >
            <CommentIndicator />
          </div>
        )}
        {/* CommentsPortal is handled by the main Table component */}
      </>
    );
  };
};
