import React, { useState, useEffect, useRef, useMemo } from "react";
import { createPortal } from "react-dom";
import moment from "moment";
import { Avatar } from "../Avatar";
import { Button } from "../Button";
import { ReactComponent as CloseIcon } from "../../assets/close.svg";
import { ReactComponent as MenuIcon } from "../../assets/MoreHorizontal.svg";
import { ReactComponent as SuccessIcon } from "../../assets/success-gray.svg";
import { ReactComponent as SuccessFillIcon } from "../../assets/success-fill.svg";
import NoComments from "./NoComments";
import { toInnerHTML } from "../../utils/html";
import { getUserAvatarColor } from "../../utils/avatarColor";
const CommentsPortal = ({
  isOpen,
  onClose,
  comments,
  onAddComment,
  cellId,
  position,
  author = "Current User",
  onMouseEnter,
  onMouseLeave,
  openedBy,
  onMenuClick,
  onMarkAsReadClick,
  onMarkAsResolvedClick,
  editCommentText = "",
  isLoading = false,
  error = null,
  onClearError,
  currentAuthor,
  editingComment = null, // Add editing comment prop
  onUpdateComment = null, // Add update comment handler
  setEditingComment,
  loadParticipantsAvatar,
  resolvedComments = [],
  messageId = null,
  configuration,
}) => {
  if (!isOpen) return null;

  const [openFullReplies, setOpenFullReplies] = useState(openedBy == "click");
  // const [dynamicMaxHeight, setDynamicMaxHeight] = useState(500);
  const [adjustedPosition, setAdjustedPosition] = useState(position);
  const [editingText, setEditingText] = useState(""); // Local state for editing text
  const listRef = useRef(null);

  // Initialize editing text when editing comment changes
  useEffect(() => {
    if (editingComment) {
      setEditingText(editingComment.text || "");
    }
  }, [editingComment]);

  // useEffect(() => {
  //   if (isOpen) {
  //     const gridEl = document.querySelector(".ag-root");
  //     if (gridEl) {
  //       const gridRect = gridEl.getBoundingClientRect();
  //       const availableHeight = gridRect.bottom - adjustedPosition.top - 10; // 10px margin
  //       setDynamicMaxHeight(Math.min(availableHeight, 500));
  //     }
  //   }
  // }, [isOpen, adjustedPosition]);

  // Recalculate position when expanding from hover to full view to keep within viewport
  useEffect(() => {
    if (openFullReplies && comments && comments.length > 0) {
      const safePad = 8; // small viewport padding
      if (comments.length === 1) {
        // Only adjust specially for single-comment case based on text length
        const headerHeight = 50;
        const inputSectionHeight = 60;
        const metaHeight = 40; // avatar/author/timestamp row
        const lineHeight = 20;
        const charsPerLine = 45;
        const textLen = (comments[0]?.text || "").length;
        const lines = Math.max(1, Math.ceil(textLen / charsPerLine));
        const textHeight = Math.min(lines * lineHeight, 300); // cap large texts
        const desiredHeight = Math.min(
          headerHeight + metaHeight + textHeight + inputSectionHeight,
          500
        );
        const viewportHeight =
          window.innerHeight || document.documentElement.clientHeight;
        // Always base off latest provided position to avoid reusing stale adjustedPosition
        const baseTop = position?.top ?? 0;
        const fitsBelow = baseTop + desiredHeight <= viewportHeight - safePad;
        const keepTop = Math.max(safePad, baseTop);
        const clampTop = Math.max(
          safePad,
          viewportHeight - desiredHeight - safePad
        );
        const newTop = fitsBelow ? keepTop : clampTop;
        setAdjustedPosition({
          top: newTop,
          left: position?.left ?? 0,
        });
      } else {
        // Leave other cases as before: use fixed desiredHeight=500 and clamp from position.top
        const desiredHeight = 500;
        const viewportHeight =
          window.innerHeight || document.documentElement.clientHeight;
        const maxTop = Math.max(
          safePad,
          viewportHeight - desiredHeight - safePad
        );
        const newTop = Math.min(Math.max(safePad, position?.top || 0), maxTop);
        setAdjustedPosition({ top: newTop, left: position?.left || 0 });
      }
    } else {
      // Use original position for hover or no comments
      setAdjustedPosition(position);
    }
  }, [openFullReplies, comments, position]);

  // Auto-scroll to specific message or bottom when the portal opens
  useEffect(() => {
    if (!isOpen) return;
    const el = listRef.current;
    if (!el) return;

    // Wait for DOM to render list items
    requestAnimationFrame(() => {
      try {
        if (messageId) {
          // Scroll to specific message if messageId is provided
          const messageElement = el.querySelector(
            `[data-message-id="${messageId}"]`
          );
          if (messageElement) {
            messageElement.scrollIntoView({
              behavior: "smooth",
              block: "center",
            });

            // Add highlight effect
            messageElement.style.backgroundColor = "#eceefd";
            messageElement.style.transition = "background-color 0.3s ease";

            // Remove highlight after 3 seconds
            setTimeout(() => {
              messageElement.style.backgroundColor = "";
            }, configuration?.messageIdHighlightTimer || 3000);
          } else {
            // Fallback to bottom if message not found
            if (el.scrollHeight > el.clientHeight) {
              el.scrollTo({ top: el.scrollHeight, behavior: "smooth" });
            }
          }
        } else {
          // Default behavior: scroll to bottom
          if (el.scrollHeight > el.clientHeight) {
            el.scrollTo({ top: el.scrollHeight, behavior: "smooth" });
          }
        }
      } catch (e) {
        // no-op: guard against rare layout thrash errors
      }
    });
    if (onMarkAsReadClick && !comments[0]?.read) onMarkAsReadClick(cellId);
  }, [isOpen, openFullReplies, comments?.length, messageId]);

  // Close on Escape when rendering standalone NoComments (isInsidePortal === false)
  // This corresponds to the branch where there are no comments to show.
  useEffect(() => {
    if (!isOpen) return;
    const isNoCommentsOutsidePortal = !(comments && comments.length > 0);
    if (!isNoCommentsOutsidePortal) return;

    const onKeyDown = (e) => {
      if (e.key === "Escape" || e.key === "Esc") {
        if (typeof onClose === "function") {
          onClose();
        }
      }
    };

    document.addEventListener("keydown", onKeyDown);
    return () => {
      document.removeEventListener("keydown", onKeyDown);
    };
  }, [isOpen, comments, onClose]);

  const formatTimestamp = (timestamp) => {
    if (!timestamp) return "";
    if (moment(timestamp).isValid()) {
      return moment.utc(timestamp).local().format("hh:mm A, MM-DD-YYYY");
    }
    return timestamp;
  };

  const isResolved =
    Array.isArray(resolvedComments) &&
    resolvedComments.find((comment) => comment === cellId);

  return createPortal(
    <div
      style={{
        position: "fixed",
        top: adjustedPosition?.top || 0,
        left: adjustedPosition?.left || 0,
        zIndex: 9999,
      }}
      onClick={onClose}
      onMouseEnter={onMouseEnter}
      onMouseLeave={!openFullReplies ? onMouseLeave : () => {}}
    >
      {comments && comments?.length > 0 ? (
        <div
          style={{
            maxHeight: "500px",
            paddingBottom: openFullReplies && isResolved ? "16px" : "0px",
          }} //`${dynamicMaxHeight}px`
          className={`comments-portal-container ${
            !openFullReplies ? "clickable" : ""
          } ${position?.side == "left" ? "left" : ""}`}
          onClick={(e) => {
            e.stopPropagation();
            if (!openFullReplies) {
              setOpenFullReplies(true);
            }
          }}
        >
          {/* Header */}
          {openFullReplies && (
            <div
              className={`comments-portal-header ${
                position?.side == "left" ? "left" : ""
              }`}
            >
              <div className="comments-portal-header-inner">
                <h3>Comments</h3>
                <div className="comments-portal-header-buttons">
                  {comments?.length >= 1 &&
                    !isResolved &&
                    !(
                      configuration?.disableMarkAsRead &&
                      configuration?.disableDeleteThread
                    ) && (
                      <Button
                        className=""
                        size="small"
                        variant="text"
                        disabled={false}
                        icon={<MenuIcon fontSize="small" />}
                        iconPlacement="left"
                        type="default"
                        style={{
                          backgroundColor: "transparent",
                          maxHeight: "32px",
                        }}
                        onClick={(e) => {
                          onMenuClick(e, cellId, "topMenu");
                        }}
                      />
                    )}
                  {!configuration?.disableMarkAsResolved &&
                    (isResolved ? (
                      <SuccessFillIcon fontSize="small" />
                    ) : (
                      <div
                        onClick={(e) => {
                          e.stopPropagation();
                          if (onMarkAsResolvedClick)
                            onMarkAsResolvedClick(cellId, comments);
                        }}
                        style={{ cursor: "pointer" }}
                      >
                        <SuccessIcon fontSize="small" />
                      </div>
                    ))}
                  <Button
                    className="comment-close"
                    size="small"
                    variant="text"
                    disabled={false}
                    icon={<CloseIcon fontSize={"large"} />}
                    iconPlacement="left"
                    type="default"
                    onClick={onClose}
                    style={{
                      backgroundColor: "transparent",
                      padding: "4px 0px",
                    }}
                  />
                </div>
              </div>
            </div>
          )}

          {/* Comments List */}
          <div className="comments-portal-list" ref={listRef}>
            {comments.map((comment, index) => {
              const isCurrentAuthor = comment.author === currentAuthor;
              if (!openFullReplies && index > 0) {
                return null;
              }
              return (
                <div key={comment.id} data-message-id={comment.id}>
                  {/* First Row: Avatar, Author, Timestamp, and Menu */}
                  <div className="comment-item-row-1">
                    <div className="comment-item-author-section">
                      <Avatar
                        size="small"
                        type="withoutPicture"
                        label={comment.author}
                        className="comment-item-avatar"
                        style={{
                          width: "6px",
                          height: "26px",
                          borderRadius: "6px",
                          padding: "3px 13px",
                          backgroundColor: getUserAvatarColor(comment.author),
                        }}
                      />
                      <div className="comment-item-author-name">
                        {comment.author}
                      </div>
                      <div className="comment-item-timestamp">
                        {formatTimestamp(comment.timestamp)}
                        {comment.isEdited && <span>(edited)</span>}
                      </div>
                    </div>

                    {/* Three dots menu */}
                    {openFullReplies &&
                      isCurrentAuthor &&
                      (!configuration?.disableEditComment ||
                        !configuration?.disableDeleteComment) && (
                        <Button
                          className=""
                          size="small"
                          variant="text"
                          disabled={false}
                          icon={<MenuIcon fontSize="small" />}
                          iconPlacement="left"
                          type="default"
                          style={{ backgroundColor: "transparent" }}
                          onClick={(e) => {
                            onMenuClick(e, comment);
                          }}
                        />
                      )}
                  </div>

                  {/* Second Row: Comment Text or Edit Input */}
                  <div className="comment-item-row-2">
                    {/* Invisible avatar placeholder for alignment */}
                    {/* <div className="comment-item-avatar-placeholder" /> */}
                    {editingComment && editingComment.id === comment.id ? (
                      /* Show input field when editing this comment */
                      <div className="comment-edit-input-wrapper">
                        <NoComments
                          onAddComment={onUpdateComment}
                          cellId={comment.id}
                          position={position}
                          editCommentText={editingText}
                          isLoading={isLoading}
                          error={error}
                          onClearError={onClearError}
                          onUpdateComment={(text) =>
                            onUpdateComment(comment.id, text)
                          }
                          isEditFlow={true}
                          isInsidePortal={true}
                          setEditingComment={setEditingComment}
                          loadParticipantsAvatar={loadParticipantsAvatar}
                        />
                      </div>
                    ) : (
                      /* Show normal comment text */
                      <div
                        className={`comment-item-text`}
                        dangerouslySetInnerHTML={toInnerHTML(comment.text)}
                      />
                    )}
                  </div>
                </div>
              );
            })}
          </div>
          {openFullReplies && !isResolved && (
            <div className="add-comment-section">
              <Avatar
                size="small"
                type="withoutPicture"
                label={currentAuthor}
                className="comment-item-avatar"
                style={{
                  width: "6px",
                  height: "26px",
                  borderRadius: "6px",
                  padding: "3px 13px",
                  backgroundColor: getUserAvatarColor(currentAuthor),
                }}
              />
              <NoComments
                onAddComment={onAddComment}
                cellId={cellId}
                position={position}
                isInsidePortal={true}
                isLoading={isLoading}
                error={error}
                onClearError={onClearError}
                loadParticipantsAvatar={loadParticipantsAvatar}
              />
            </div>
          )}
        </div>
      ) : (
        <NoComments
          onAddComment={onAddComment}
          cellId={cellId}
          position={position}
          editCommentText={editCommentText}
          isLoading={isLoading}
          error={error}
          onClearError={onClearError}
          loadParticipantsAvatar={loadParticipantsAvatar}
        />
      )}
    </div>,
    document.body
  );
};

export default CommentsPortal;
