import React, {
  useState,
  useEffect,
  useRef,
  useCallback,
  useMemo,
} from "react";
import { Button } from "../Button";
// import { ReactComponent as ChatBotSendIcon } from "../../assets/comment-send.svg";
import ChatBotSendIcon from "@mui/icons-material/North";
import { MentionEditor } from "../common/MentionEditor";

// Helper function to extract mentioned users from TipTap editor JSON
const extractMentionedUsers = (editorJSON) => {
  const mentionedUsers = [];

  const traverseNodes = (node) => {
    if (node.type === "mention" && node.attrs) {
      // Extract user information from mention node
      const user = {
        id: node.attrs.id,
        name: node.attrs.label || node.attrs.name,
        ...(node.attrs.avatar && { avatar: node.attrs.avatar }),
        ...(node.attrs.status && { status: node.attrs.status }),
      };

      // Avoid duplicates by checking if user is already in the array
      if (!mentionedUsers.find((u) => u.id === user.id)) {
        mentionedUsers.push(user);
      }
    }

    // Recursively traverse child nodes
    if (node.content && Array.isArray(node.content)) {
      node.content.forEach(traverseNodes);
    }
  };

  // Start traversal from the root
  if (editorJSON && editorJSON.content) {
    editorJSON.content.forEach(traverseNodes);
  }

  return mentionedUsers;
};

const NoComments = ({
  onAddComment,
  cellId,
  position,
  isInsidePortal = false,
  editCommentText = "",
  isLoading = false,
  error = null,
  onClearError,
  isEditFlow,
  onUpdateComment,
  setEditingComment,
  loadParticipantsAvatar,
}) => {
  const [inputValue, setInputValue] = useState(editCommentText);
  const inputRef = useRef(null);
  const [isFixed, setIsFixed] = useState(false);
  const [isScrollable, setIsScrollable] = useState(false);
  const [height, setHeight] = useState("auto");
  const [isMultiLine, setIsMultiLine] = useState(false);
  const MAX_HEIGHT = 142; // Match CSS max-height for textarea

  const editorRef = useRef(null);
  // Use refs to track previous values and prevent infinite loops
  const prevHeightRef = useRef(null);
  const isUpdatingRef = useRef(false);

  const checkMultiLineContent = useCallback(() => {
    if (!editorRef.current?.editor) return;

    try {
      // Get the editor DOM element
      const editorElement = editorRef.current.editor.view.dom;
      if (!editorElement) return;

      // Get the computed line height and actual height
      const computedStyle = window.getComputedStyle(editorElement);
      const lineHeight = parseFloat(computedStyle.lineHeight) || 20;
      const actualHeight = editorElement.scrollHeight;

      // Check if content spans more than one line
      // Adding a small tolerance to account for padding and minor variations
      const isContentMultiLine = actualHeight > lineHeight * 1.5;

      setIsMultiLine(isContentMultiLine);
    } catch (error) {
      console.warn("Error checking multi-line content:", error);
    }
  }, []);

  useEffect(() => {
    if (inputValue === "") {
      setIsFixed(false);
      setIsScrollable(false);
      // Reset the height tracking
      prevHeightRef.current = null;
    }
  }, [inputValue]);

  useEffect(() => {
    if (editCommentText === null) {
      setInputValue("");
    } else {
      setInputValue(editCommentText);
    }
  }, [editCommentText]);

  // Autofocus on MentionEditor when component becomes visible
  // while preserving table cell focus using custom styling
  useEffect(() => {
    let cellElement = null;
    let styleElement = null;

    const timer = setTimeout(() => {
      if (editorRef.current?.focus) {
        // Capture the currently focused cell
        cellElement = document.querySelector(".ag-cell-focus");

        if (cellElement) {
          // Get the cell's position to create a unique selector
          const rowIndex = cellElement
            .closest(".ag-row")
            ?.getAttribute("row-index");
          const colId = cellElement.getAttribute("col-id");

          if (rowIndex && colId) {
            // Create custom CSS to maintain visual focus for this specific cell
            const customCSS = `
              .ag-row[row-index="${rowIndex}"] .ag-cell[col-id="${colId}"]:after {
                content: " ";
                position: absolute;
                top: 0;
                bottom: 0;
                width: 3px;
                background: #4259ee;
                left: 0;
              }
            `;

            // Create and inject the style element
            styleElement = document.createElement("style");
            styleElement.textContent = customCSS;
            styleElement.setAttribute("data-comment-focus", "true");
            document.head.appendChild(styleElement);

            // Mark the cell as comment-focused
            cellElement.setAttribute("data-comment-focused", "true");
          }
        }

        // Focus the input for typing
        editorRef.current.focus({ preventScroll: true });
      }
    }, 50);

    // Cleanup function
    return () => {
      clearTimeout(timer);
      if (styleElement) {
        document.head.removeChild(styleElement);
      }
      if (cellElement) {
        cellElement.removeAttribute("data-comment-focused");
      }
    };
  }, []);

  const handleAddComment = (e) => {
    e.stopPropagation();
    if (inputValue.trim() && !isLoading) {
      // Extract mentioned users from the editor content
      let taggedUsers = [];
      try {
        if (editorRef.current?.editor) {
          const editorJSON = editorRef.current.editor.getJSON();
          taggedUsers = extractMentionedUsers(editorJSON);
        }
      } catch (error) {
        console.warn("Error extracting mentioned users:", error);
      }

      onAddComment(cellId, inputValue, taggedUsers);
      setInputValue("");
    }
  };

  const handleInputChange = (e) => {
    // const el = e.target;
    // const newVal = el.value;
    setInputValue(e);
    // Clear error when user starts typing
    if (error && onClearError) {
      onClearError();
    }

    // Check for multi-line content after a short delay to allow DOM to update
    setTimeout(() => {
      checkMultiLineContent();
    }, 0);
  };

  return (
    <div
      className={`no-comments-container ${
        isInsidePortal ? "in-portal" : "as-banner"
      } ${isFixed ? "stacked" : ""} ${
        !isFixed || inputValue === "" ? "empty" : ""
      } ${!isFixed ? "single-line-textarea" : ""}`}
      style={
        !isInsidePortal
          ? {
              top: position?.top,
              left: position?.left,
              maxHeight: "182px", // Match chat-input-wrapper max-height
            }
          : {
              gap: "10px",
              maxHeight: "182px",
            }
      }
      onClick={(e) => e.stopPropagation()}
    >
      <div
        className="comment-input-wrapper"
        style={{
          flexDirection: isMultiLine ? "column" : "row",
          gap: isMultiLine ? "8px" : "0",
        }}
      >
        <MentionEditor
          ref={editorRef}
          value={inputValue}
          onChange={handleInputChange}
          onSend={handleAddComment}
          placeholder="Type message..."
          disabled={isLoading}
          maxLength={1000}
          chatId={cellId}
          loadParticipantsAvatar={loadParticipantsAvatar}
          isMultiLine={isMultiLine}
        />
        {isLoading ? (
          <div className="ia-btn-loading-icon">
            <span className={`ia-btn-loading-track ia-btn-loading-light`} />
          </div>
        ) : (
          !isEditFlow && (
            <Button
              variant="primary"
              onClick={handleAddComment}
              icon={<ChatBotSendIcon />}
              disabled={isLoading || !inputValue}
              loading={isLoading}
              size="small"
              style={{ display: "flex" }}
            />
          )
        )}
      </div>
      {isEditFlow && (
        <div style={{ display: "flex", gap: "10px" }}>
          <Button
            variant="tertiary"
            size="small"
            onClick={() => {
              setInputValue("");
              setEditingComment(null);
            }}
            disabled={isLoading}
            loading={isLoading}
          >
            Cancel
          </Button>
          <Button
            variant="primary"
            size="small"
            onClick={() => onUpdateComment(inputValue)}
            disabled={isLoading}
            loading={isLoading}
          >
            Save
          </Button>
        </div>
      )}
    </div>
  );
};

export default NoComments;
