import React, { useRef, useEffect, useState, useCallback } from "react";
import { Prompt } from "../../../Prompt";
import { ChatHeader } from "./ChatHeader/ChatHeader";
import { ChatInput } from "./ChatInput/ChatInput";
import { DateSeparator } from "./DateSeparator/DateSeparator";
import { ChatMessage } from "./ChatMessages/ChatMessage";
import { ReplyBadge } from "./ReplyBadge/ReplyBadge";
import { Button } from "../../../Button";
import "./TableChatRightSection.styles.scss";
import { SkeletonList } from "../SkeletonList";
import { Loader } from "../../../Loader";
import useInfiniteScroll from "../../hooks/useInfiniteScroll";
import { Modal } from "../../../Modal";
import { Avatar } from "../../../Avatar";
import { Checkbox } from "../../../Checkbox";
import { Input } from "../../../Input";
import SearchIcon from "../../../../assets/searchIcon.svg";
import { EmptyContainer } from "../../EmptyContainer";
import ChatMessageListSkeleton from "../ChatMessageSkeleton/ChatMessageListSkeleton";

const TableChatRightSection = ({
  // Header props
  title,
  chatId,
  CreatedBy,
  createdAt,
  participants = [],
  participantsList = [],
  onParticipantsClick,

  // Messages props
  messages: propMessages = [],

  // Input props
  placeholder = "Type message",
  showFormatting = true,
  maxLength = 5000,

  // // Event handlers
  // onSend,
  onMessageReply,
  onMessageBookmark,
  onMessagePin,
  onMessageMore,
  onAttachFile,
  onImageUpload,
  onEmojiClick,
  setPinnedMessages,

  // Customization
  className = "",
  showDateSeparators = true,
  autoScroll = true,
  onThreadClick,

  // External configuration
  messageConfig = {},
  inputChatConfig = {},
  ...restProps
}) => {
  console.log("showQuickAction", inputChatConfig);
  const messagesRef = useRef(null);
  const isLoadingRef = useRef(false);
  const [inputValue, setInputValue] = useState("");
  const [messages, setMessages] = useState(propMessages);
  const [showClearChat, setShowClearChat] = useState(false);

  // Edit mode state
  const [isEditMode, setIsEditMode] = useState(false);
  const [editingMessage, setEditingMessage] = useState(null);

  // Search state
  const [searchResults, setSearchResults] = useState([]);
  const [isSearchActive, setIsSearchActive] = useState(false);
  const [searchQuery, setSearchQuery] = useState("");
  const [isSearchLoading, setIsSearchLoading] = useState(false);
  const [isClearChatLoading, setIsClearChatLoading] = useState(false);
  const [addMembers, setAddMembers] = useState([]);
  const [memberList, setMemberList] = useState([]);
  const [showAddMembers, setShowAddMembers] = useState(false);
  const [showAddMembersLoading, setShowAddMembersLoading] = useState(false);
  const [externalSavingMembers, setExternalSavingMembers] = useState(false);
  const [memberSearchQuery, setMemberSearchQuery] = useState("");
  const [filteredMemberList, setFilteredMemberList] = useState([]);
  const [highlightedMessageId, setHighlightedMessageId] = useState(null);
  const searchCompletedRef = useRef(false); // Single flag to prevent any re-execution
  const currentChatIdRef = useRef(null); // Track current chat to reset on chat change
  const lastHighlightedMessageIdRef = useRef(null); // Track last highlighted message to prevent duplicates

  // Extract real-time props from messageConfig
  const realTimeMessages = messageConfig?.realTimeMessages || [];
  const isWebSocketConnected = messageConfig?.isWebSocketConnected || false;
  const currentTopicId = messageConfig?.currentTopicId || null;
  const onRealTimeMessageUpdate =
    messageConfig?.onRealTimeMessageUpdate || null;
  const currentUserId = messageConfig?.currentUserId || null;
  const selectedMessageId = messageConfig?.selectedMessageId || null;

  // Extract highlight configuration with defaults
  const maxSearchPages = messageConfig?.maxSearchPages || 3;
  const highlightDuration = messageConfig?.highlightDuration || 3000;
  const scrollBehavior = messageConfig?.scrollBehavior || "smooth";
  const scrollBlock = messageConfig?.scrollBlock || "center";
  const highlightColor = messageConfig?.highlightColor || null; // null means use CSS default
  const highlightTrigger = messageConfig?.highlightTrigger; // Trigger for pinned message re-highlighting

  // Create fetchMore function for infinite scroll
  const fetchMoreMessages = useCallback(
    async (page) => {
      if (!messageConfig?.loadMessages || !chatId) {
        return [];
      }

      try {
        const result = await messageConfig.loadMessages(chatId, page);

        // Handle both old format (array) and new format (object with messages and noMoreData)
        let newMessages, noMoreData;
        if (Array.isArray(result)) {
          // Old format - just an array of messages
          newMessages = result;
          noMoreData = !result || result.length === 0;
        } else {
          // New format - object with messages and noMoreData flag
          newMessages = result?.messages || [];
          noMoreData = result?.noMoreData || false;
        }

        // If noMoreData flag is set, stop infinite scroll
        if (noMoreData) {
          return [];
        }

        // If no messages returned, we've reached the end
        if (!newMessages || newMessages.length === 0) {
          return [];
        }

        // Add new messages to the beginning of the existing messages (for older messages)
        setMessages((prevMessages) => {
          // Filter out duplicates based on message ID
          const existingIds = new Set(prevMessages.map((msg) => msg.id));
          const uniqueNewMessages = newMessages.filter(
            (msg) => !existingIds.has(msg.id)
          );

          // Prepend new messages to the beginning (older messages)
          return [...uniqueNewMessages, ...prevMessages];
        });

        return newMessages;
      } catch (error) {
        console.error(
          "[TableChatRightSection] Error fetching more messages:",
          error
        );
        // Return empty array on error to stop infinite scroll
        return [];
      }
    },
    [messageConfig?.loadMessages, chatId]
  );

  // Initialize infinite scroll hook with a delay to prevent initial triggering
  const [enableInfiniteScroll, setEnableInfiniteScroll] = useState(false);

  const {
    loadMoreRef,
    isLoading: isLoadingMore,
    hasMore,
    error: infiniteScrollError,
    reset: resetInfiniteScroll,
    updateHasMore,
    updateCurrentPage, // Update page when manually loading pages
    currentPage, // Track current page for smart message searching
  } = useInfiniteScroll(fetchMoreMessages, {
    threshold: 0.1,
    rootMargin: "200px 0px 0px 0px", // Only trigger when scrolling near the top
    enabled: enableInfiniteScroll && !!chatId,
  });

  // Enable infinite scroll after initial load is complete
  useEffect(() => {
    if (chatId) {
      const timer = setTimeout(() => {
        setEnableInfiniteScroll(true);
      }, 2000); // 2 second delay after initial load

      return () => clearTimeout(timer);
    } else {
      setEnableInfiniteScroll(false);
    }
  }, [chatId]);

  // Watch for messages cleared trigger and clear messages immediately
  useEffect(() => {
    const trigger = messageConfig?.messagesClearedTrigger;
    if (trigger && trigger > 0 && chatId) {
      // Immediately clear messages when messages_cleared WebSocket event is received
      setMessages([]);

      // Reset infinite scroll state
      resetInfiniteScroll();
      updateHasMore(false);

      // Optionally, also reload from API after a short delay to ensure consistency
      // This is useful if the WebSocket event arrives before the API is updated
      const reloadFromAPI = async () => {
        try {
          if (messageConfig?.loadMessages && chatId) {
            const result = await messageConfig.loadMessages(
              chatId,
              1 // Start with page 1
            );

            // Handle both old format (array) and new format (object with messages)
            let reloadedMessages;
            if (Array.isArray(result)) {
              // Old format - just an array of messages
              reloadedMessages = result;
            } else {
              // New format - object with messages and noMoreData flag
              reloadedMessages = result?.messages || [];
            }

            // Only update if we still have messages (API might not be updated yet)
            if (reloadedMessages && reloadedMessages.length > 0) {
              setMessages(reloadedMessages);
              updateHasMore(true);
            } else {
              console.log(
                "[TableChatRightSection] API confirmed messages are cleared"
              );
              // Keep messages empty as set above
            }
          }
        } catch (error) {
          console.error(
            "[TableChatRightSection] Error reloading messages after clear:",
            error
          );
          // Keep messages empty as set above
        }
      };

      // Delay the API reload to give the server time to process the clear operation
      setTimeout(reloadFromAPI, 1000);
    }
  }, [
    messageConfig?.messagesClearedTrigger,
    chatId,
    messageConfig?.loadMessages,
    resetInfiniteScroll,
    updateHasMore,
  ]);

  // Load messages when chatId changes
  useEffect(() => {
    const loadMessages = async () => {
      // Prevent multiple simultaneous loads
      if (isLoadingRef.current) {
        return;
      }

      if (chatId && messageConfig?.loadMessages) {
        isLoadingRef.current = true;

        // Reset search flag when chat changes
        if (currentChatIdRef.current !== chatId) {
          searchCompletedRef.current = false;
          lastHighlightedMessageIdRef.current = null; // Reset highlighted message tracking
          currentChatIdRef.current = chatId;
        }

        try {
          // Reset infinite scroll state for new chat
          setEnableInfiniteScroll(false);
          resetInfiniteScroll();

          const result = await messageConfig.loadMessages(
            chatId,
            1 // Start with page 1
          );

          // Handle both old format (array) and new format (object with messages)
          let initialMessages;
          if (Array.isArray(result)) {
            // Old format - just an array of messages
            initialMessages = result;
          } else {
            // New format - object with messages and noMoreData flag
            initialMessages = result?.messages || [];
          }

          setMessages(initialMessages || []);

          // If page 1 returns empty array, disable infinite scroll completely
          if (!initialMessages || initialMessages.length === 0) {
            updateHasMore(false); // Disable infinite scroll when no initial data
          }
        } catch (error) {
          console.error(
            "[TableChatRightSection] Error loading messages:",
            error
          );
          setMessages([]);
        } finally {
          isLoadingRef.current = false;
        }
      } else {
        setMessages([]);
      }
    };

    loadMessages();

    // Cleanup function to reset loading state
    return () => {
      isLoadingRef.current = false;
    };
  }, [chatId, resetInfiniteScroll, updateHasMore]); // Added resetInfiniteScroll and updateHasMore to dependencies

  // Effect to find and highlight selected message
  useEffect(() => {
    // Early exit if no selectedMessageId or chatId
    if (!selectedMessageId || !chatId) {
      return;
    }

    // Wait for initial messages to load
    if (messages.length === 0) {
      return;
    }

    // Check if we've already highlighted this exact message
    // BUT: Allow re-highlighting if this is a pinned message click (highlightTrigger exists)
    const isPinnedMessageHighlight =
      highlightTrigger !== null && highlightTrigger !== undefined;

    if (
      !isPinnedMessageHighlight &&
      lastHighlightedMessageIdRef.current === selectedMessageId
    ) {
      return;
    }

    // FIRST: Quick check if message already exists (synchronous)
    const messageExistsImmediately = messages.some(
      (msg) => msg.id === selectedMessageId
    );

    if (messageExistsImmediately) {
      // Mark this message as highlighted ONLY for config-based highlights (not pinned)
      if (!isPinnedMessageHighlight) {
        lastHighlightedMessageIdRef.current = selectedMessageId;
      }

      // Message already loaded - just highlight it
      setEnableInfiniteScroll(false);

      // Small delay to ensure DOM is ready for scrolling
      setTimeout(() => {
        scrollToMessage(selectedMessageId);
        setHighlightedMessageId(selectedMessageId);

        // Clear highlight after duration
        setTimeout(() => setHighlightedMessageId(null), highlightDuration);

        // Re-enable infinite scroll after fixed delay
        setTimeout(() => {
          setEnableInfiniteScroll(true);
        }, 2000); // Fixed 2 second delay
      }, 100); // Small delay for DOM to be ready

      return; // Don't proceed with search logic
    }

    // Message NOT in current list - now we need to search

    // Disable infinite scroll during search
    setEnableInfiniteScroll(false);

    // Start search immediately
    findAndHighlightMessage();

    async function findAndHighlightMessage() {
      // Message not found in current list - need to search
      // Check if we've already done a search to prevent duplicate API calls
      if (searchCompletedRef.current) {
        setEnableInfiniteScroll(true);
        return;
      }

      // Mark as completed to prevent duplicate searches
      searchCompletedRef.current = true;

      // Get current page and calculate next page to search
      const startPage = currentPage + 1;

      // If we're already at or beyond maxSearchPages, no point searching
      if (currentPage >= maxSearchPages) {
        setEnableInfiniteScroll(true);
        return;
      }

      let messageFoundInSearch = false;

      try {
        for (let page = startPage; page <= maxSearchPages; page++) {
          // Check if we already found it
          if (messageFoundInSearch) {
            break;
          }

          if (!messageConfig?.loadMessages) break;

          const result = await messageConfig.loadMessages(chatId, page);

          let pageMessages;
          if (Array.isArray(result)) {
            pageMessages = result;
          } else {
            pageMessages = result?.messages || [];
          }

          if (!pageMessages || pageMessages.length === 0) {
            break;
          }

          const foundMessage = pageMessages.find(
            (msg) => msg.id === selectedMessageId
          );

          if (foundMessage) {
            messageFoundInSearch = true; // Mark as found

            // Mark this message as highlighted ONLY for config-based highlights (not pinned)
            if (!isPinnedMessageHighlight) {
              lastHighlightedMessageIdRef.current = selectedMessageId;
            }

            // Update the current page in infinite scroll hook
            updateCurrentPage(page);

            // Add messages
            setMessages((prevMessages) => {
              const existingIds = new Set(prevMessages.map((msg) => msg.id));
              const uniqueNewMessages = pageMessages.filter(
                (msg) => !existingIds.has(msg.id)
              );
              return [...uniqueNewMessages, ...prevMessages];
            });

            // Wait for DOM to render new messages, then scroll and highlight
            // Use double requestAnimationFrame to ensure DOM is fully updated
            requestAnimationFrame(() => {
              requestAnimationFrame(() => {
                setTimeout(() => {
                  scrollToMessage(selectedMessageId);
                  setHighlightedMessageId(selectedMessageId);

                  // Clear highlight after duration
                  setTimeout(
                    () => setHighlightedMessageId(null),
                    highlightDuration
                  );

                  // Re-enable infinite scroll after fixed delay
                  setTimeout(() => {
                    setEnableInfiniteScroll(true);
                  }, 2000); // Fixed 2 second delay
                }, 300); // Small delay to ensure DOM is fully updated
              });
            });

            break; // Exit the loop immediately
          }
        }

        if (!messageFoundInSearch) {
          setEnableInfiniteScroll(true);
        }
      } catch (error) {
        console.error(
          "[TableChatRightSection] Error searching for message:",
          error
        );
        setEnableInfiniteScroll(true);
      }
    }
  }, [selectedMessageId, chatId, messages.length, highlightTrigger]); // Re-run when trigger changes (pinned message clicks)

  // Helper function to scroll to a specific message
  const scrollToMessage = (messageId) => {
    const messageElement = document.querySelector(
      `[data-message-id="${messageId}"]`
    );

    if (messageElement && messagesRef.current) {
      // Scroll the message into view with configured behavior
      messageElement.scrollIntoView({
        behavior: scrollBehavior,
        block: scrollBlock,
      });
    }
  };

  // Auto-scroll to bottom when new messages arrive
  useEffect(() => {
    if (autoScroll && messagesRef.current) {
      messagesRef.current.scrollTop = messagesRef.current.scrollHeight;
    }
  }, [messages.length, autoScroll]);

  // Handle real-time message updates
  useEffect(() => {
    if (realTimeMessages.length > 0 && chatId === currentTopicId) {
      setMessages((prevMessages) => {
        // Create a map of existing messages by ID for quick lookup
        const existingMessagesMap = new Map(
          prevMessages.map((msg) => [msg.id, msg])
        );

        // Process each real-time message
        const updatedMessages = [...prevMessages];
        let hasChanges = false;

        realTimeMessages.forEach((realTimeMsg) => {
          const existingMsg = existingMessagesMap.get(realTimeMsg.id);

          if (existingMsg) {
            // Message exists - update it

            const msgIndex = updatedMessages.findIndex(
              (msg) => msg.id === realTimeMsg.id
            );
            if (msgIndex !== -1) {
              updatedMessages[msgIndex] = {
                ...updatedMessages[msgIndex],
                ...realTimeMsg,
                // Preserve some original properties that shouldn't be overwritten
                author: realTimeMsg.author || updatedMessages[msgIndex].author,
                authorName:
                  realTimeMsg.authorName ||
                  updatedMessages[msgIndex].authorName,
                senderId:
                  realTimeMsg.senderId || updatedMessages[msgIndex].senderId,
                // Preserve deleted state
                deleted:
                  realTimeMsg.deleted !== undefined
                    ? realTimeMsg.deleted
                    : updatedMessages[msgIndex].deleted,
                otherProps: {
                  ...updatedMessages[msgIndex].otherProps,
                  ...realTimeMsg.otherProps,
                  sender_id:
                    realTimeMsg.otherProps?.sender_id ||
                    updatedMessages[msgIndex].otherProps?.sender_id,
                  // Preserve deleted state in otherProps as well
                  deleted:
                    realTimeMsg.otherProps?.deleted !== undefined
                      ? realTimeMsg.otherProps.deleted
                      : updatedMessages[msgIndex].otherProps?.deleted,
                },
              };
              hasChanges = true;
            }
          } else {
            // Message doesn't exist - add it as new

            updatedMessages.push(realTimeMsg);
            hasChanges = true;
          }
        });

        if (hasChanges) {
          // Sort all messages by timestamp to ensure proper chronological order
          const sortedMessages = updatedMessages.sort((a, b) => {
            const timeA = new Date(
              a.timestamp || a.date || a.created_at || a.otherProps?.created_at
            );
            const timeB = new Date(
              b.timestamp || b.date || b.created_at || b.otherProps?.created_at
            );
            return timeA - timeB; // Oldest first, newest last
          });

          // Auto-scroll to bottom if new messages arrive
          if (autoScroll) {
            setTimeout(() => {
              if (messagesRef.current) {
                messagesRef.current.scrollTop =
                  messagesRef.current.scrollHeight;
              }
            }, 100);
          }

          return sortedMessages;
        }

        return prevMessages;
      });
    }
  }, [realTimeMessages, chatId, currentTopicId, autoScroll]);

  const handleSend = async (payload) => {
    if (isEditMode && editingMessage) {
      // Handle message update
      await handleUpdateMessage(payload);
    } else if (inputChatConfig?.onSend) {
      // Handle new message creation
      try {
        const response = await inputChatConfig?.onSend(payload, chatId);

        // For new messages, always use onRealTimeMessageUpdate callback
        // since new messages are typically real-time messages
        if (onRealTimeMessageUpdate && response) {
          onRealTimeMessageUpdate(response);
        }

        // Clear the input value after successful send
        setInputValue("");
      } catch (error) {
        console.error("Error sending message:", error);
        // Don't clear input on error - let user retry
      }
    } else {
      // If no onSend handler, still clear the input
      setInputValue("");
    }
  };

  const handleUpdateMessage = async (updatedContent) => {
    if (messageConfig?.onMessageUpdate && editingMessage) {
      try {
        const response = await messageConfig?.onMessageUpdate(
          editingMessage.id,
          updatedContent
        );

        // Exit edit mode after successful update
        exitEditMode();

        // Check if the message being edited is a real-time message
        const isRealTimeMessage =
          editingMessage.isRealTime || editingMessage.otherProps?.isRealTime;

        if (isRealTimeMessage) {
          // For real-time messages: use onRealTimeMessageUpdate callback
          if (onRealTimeMessageUpdate && response) {
            onRealTimeMessageUpdate(response);
          }
        } else {
          // For API messages: update local state with response
          if (response) {
            setMessages((prevMessages) => {
              return prevMessages.map((msg) => {
                if (msg.id === editingMessage.id) {
                  return response;
                }
                return msg;
              });
            });
          }
        }
      } catch (error) {
        console.error("Error updating message:", error);
      }
    }
  };

  const handleEditMessage = (message) => {
    setIsEditMode(true);
    setEditingMessage(message);
    setInputValue(message.content || "");
  };

  const exitEditMode = () => {
    setIsEditMode(false);
    setEditingMessage(null);
    setInputValue("");
  };

  const handleReply = async (messageId) => {
    if (inputChatConfig?.onMessageReply) {
      await inputChatConfig?.onMessageReply(messageId, chatId);
    }
  };

  const handleBookmark = async (messageId) => {
    if (inputChatConfig?.onMessageBookmark) {
      await inputChatConfig?.onMessageBookmark(messageId, chatId);
    }
  };

  const handlePin = async (messageId, pinned, chatId, item) => {
    try {
      const response = await messageConfig?.onMessagePin?.(
        messageId,
        pinned,
        chatId,
        item
      );

      return response;
    } catch (error) {
      console.error("Error pinning message:", error);
    }
  };

  const handleMore = async (messageId) => {
    if (inputChatConfig?.onMessageMore) {
      await inputChatConfig?.onMessageMore(messageId, chatId);
    }
  };

  // Helper function to mark a message as deleted in local state
  const markMessageAsDeleted = (messageId) => {
    setMessages((prevMessages) => {
      return prevMessages.map((msg) => {
        if (msg.id === messageId) {
          return {
            ...msg,
            deleted: true,
            // Keep original content for display purposes
            content: msg.content,
            // Preserve all important fields for proper rendering
            timestamp: msg.timestamp,
            date: msg.date,
            created_at: msg.created_at,
            author: msg.author,
            authorName: msg.authorName,
            senderId: msg.senderId,
            otherProps: {
              ...msg.otherProps,
              deleted: true,
            },
          };
        }
        return msg;
      });
    });
  };

  // Handle search message functionality
  const handleSearchMessage = useCallback(
    async (searchValue, chatId) => {
      //  console.log; "[TableChatRightSection] Searching messages:", searchValue, chatId;

      if (!searchValue || searchValue.trim() === "") {
        // Clear search - show original messages
        setSearchResults([]);
        setIsSearchActive(false);
        setSearchQuery("");
        setIsSearchLoading(false);
        return;
      }

      try {
        setIsSearchActive(true);
        setSearchQuery(searchValue);
        setIsSearchLoading(true);

        // Call the search API through messageConfig
        if (messageConfig?.onSearchMessage) {
          const results = await messageConfig.onSearchMessage(
            searchValue,
            chatId
          );
          setSearchResults(results || []);
        }
      } catch (error) {
        console.error("[TableChatRightSection] Search error:", error);
        setSearchResults([]);
      } finally {
        setIsSearchLoading(false);
      }
    },
    [messageConfig?.onSearchMessage]
  );

  // Handle search clear
  const handleSearchClear = useCallback(() => {
    setSearchResults([]);
    setIsSearchActive(false);
    setSearchQuery("");
    setIsSearchLoading(false);
  }, []);

  const groupMessagesByDate = (messages) => {
    const grouped = [];
    let currentDate = null;

    messages.forEach((msg) => {
      const raw = msg.date || msg.timestamp;
      const parsed = new Date(raw);

      if (isNaN(parsed)) return;

      const rawDate = parsed.toISOString().split("T")[0]; // yyyy-mm-dd

      if (rawDate !== currentDate) {
        currentDate = rawDate;
        grouped.push({
          type: "date-separator",
          id: `date-${rawDate}-${msg.id}`,
          date: parsed, // 👈 pass Date object

          pinned: msg.pinned,
        });
      }

      grouped.push(msg);
    });

    return grouped;
  };

  const handleAllMessagesDelete = useCallback(async () => {
    try {
      if (messageConfig?.onClearAllMessages && chatId) {
        setIsClearChatLoading(true);
        const response = await messageConfig.onClearAllMessages(chatId);

        setIsClearChatLoading(false);
        // Clear local messages state
        setMessages([]);

        // Close the clear chat prompt
        setShowClearChat(false);

        // // Refetch messages to show the updated state (empty messages)
        // if (messageConfig?.loadMessages && selectedChatInfo?.id) {
        //   try {
        //     const result = await messageConfig.loadMessages(
        //       selectedChatInfo.id,
        //       selectedChatInfo,
        //       1 // Start with page 1
        //     );
        //     console.log(
        //       "[TableChatRightSection] [RESULT] [CLEAR ALL MESSAGES]:",
        //       result
        //     );

        //     // Handle both old format (array) and new format (object with messages)
        //     let refreshedMessages;
        //     if (Array.isArray(result)) {
        //       // Old format - just an array of messages

        //       refreshedMessages = result;
        //     } else {
        //       // New format - object with messages and noMoreData flag
        //       refreshedMessages = result?.messages || [];
        //     }

        //     setMessages([]);

        //     // Reset infinite scroll state for fresh start
        //     resetInfiniteScroll();

        //     // If cleared and still no messages, disable infinite scroll
        //     if (!refreshedMessages || refreshedMessages.length === 0) {
        //       updateHasMore(false);
        //     }
        //   } catch (refetchError) {
        //     // Keep messages empty if refetch fails
        //     setIsClearChatLoading(false);
        //     setMessages([]);
        //     // Still reset infinite scroll even on error
        //     resetInfiniteScroll();
        //     // Disable infinite scroll since messages are empty
        //     updateHasMore(false);
        //   }
        // }
      }
    } catch (error) {
      console.error("Error clearing all messages:", error);
      // Close the prompt even on error
      setShowClearChat(false);
    }
  }, [
    messageConfig?.onClearAllMessages,
    messageConfig?.loadMessages,
    resetInfiniteScroll,
    updateHasMore,
  ]);

  // Handle individual message deletion with proper real-time vs API message handling
  const handleMessageDelete = useCallback(
    async (messageId) => {
      try {
        const response = await messageConfig?.onMessageDelete?.(messageId);

        if (response?.isPinned) {
          setPinnedMessages((prevPinnedMessages) =>
            prevPinnedMessages.map((msg) =>
              msg.id === messageId ? { ...response } : msg
            )
          );
        }

        // Find the message being deleted to check if it's real-time
        const messageToDelete = messages.find((msg) => msg.id === messageId);
        const isRealTimeMessage =
          messageToDelete?.isRealTime ||
          messageToDelete?.otherProps?.isRealTime;

        if (isRealTimeMessage) {
          // For real-time messages: use onRealTimeMessageUpdate callback (same as updates)
          if (onRealTimeMessageUpdate && response) {
            // Create a proper deleted message object since response is just success boolean
            const deletedMessage = response;
            onRealTimeMessageUpdate(deletedMessage);
          }
        } else {
          // For API messages: mark message as deleted in local state (same as updates)
          markMessageAsDeleted(messageId);
        }

        return response;
      } catch (error) {
        console.error("[TableChatRightSection] Error deleting message:", error);
        throw error;
      }
    },
    [messages, messageConfig?.onMessageDelete, onRealTimeMessageUpdate]
  );
  const loadMemberList = async () => {
    const options = await restProps?.chatHeaderConfig?.loadParticipants?.(
      "new",
      chatId
    );

    if (options) {
      setMemberList(options); // assume: [{ id:1, label:"John" }, { id:2, label:"Jane"}]
      setFilteredMemberList(options); // Initialize filtered list with all members
    }
  };

  // Filter member list based on search query
  const handleMemberSearch = useCallback(
    (searchValue) => {
      setMemberSearchQuery(searchValue);

      if (!searchValue || searchValue.trim() === "") {
        // Show all members when search is empty
        setFilteredMemberList(memberList);
      } else {
        // Filter members based on label (case-insensitive)
        const filtered = memberList.filter((member) =>
          member.label?.toLowerCase().includes(searchValue.toLowerCase())
        );
        setFilteredMemberList(filtered);
      }
    },
    [memberList]
  );

  // Update filtered list when memberList changes
  useEffect(() => {
    if (memberSearchQuery.trim() === "") {
      setFilteredMemberList(memberList);
    } else {
      handleMemberSearch(memberSearchQuery);
    }
  }, [memberList, memberSearchQuery, handleMemberSearch]);

  useEffect(() => {
    if (showAddMembers) {
      loadMemberList();
    } else {
      // Reset search when modal closes
      setMemberSearchQuery("");
      setFilteredMemberList([]);
    }
  }, [showAddMembers, chatId]);

  const addInChat = (value) => {
    setAddMembers((prev) => {
      if (prev.includes(value)) {
        return prev.filter((item) => item !== value);
      } else {
        return [...prev, value];
      }
    });
  };

  // Use search results when search is active, otherwise use regular messages
  const messagesToDisplay = isSearchActive ? searchResults : messages;
  const groupedItems = groupMessagesByDate(messagesToDisplay);

  const saveMembersInChat = async () => {
    if (restProps?.chatHeaderConfig?.onParticipantAdd) {
      try {
        setShowAddMembersLoading(true);
        const response = await restProps?.chatHeaderConfig?.onParticipantAdd?.(
          addMembers,
          "new",
          chatId
        );
        if (response === null) {
          setShowAddMembersLoading(false);
          setExternalSavingMembers(true);
          setShowAddMembers(false);
          setAddMembers([]);
          setMemberSearchQuery("");
          setFilteredMemberList([]);
        }
      } catch (error) {
        console.error("Error saving members in chat:", error);
      } finally {
        setShowAddMembersLoading(false);
        setExternalSavingMembers(false);
      }
    }
  };

  return (
    <div className={`table-chat-right-section-container ${className}`}>
      {chatId ? (
        <ChatHeader
          title={title}
          chatId={chatId}
          createdBy={CreatedBy}
          createdAt={createdAt}
          chatHeaderConfig={{
            ...restProps?.chatHeaderConfig,
            onSearchMessage: handleSearchMessage,
            onSearchClear: handleSearchClear,
            externalSavingMembers: externalSavingMembers,
          }}
        />
      ) : null}
      {messages.length > 0 && (
        <div className="clear-chat-button-container">
          <Button
            variant="text"
            size="small"
            onClick={(event) => {
              event.stopPropagation();
              // handleMore(item.id);
              // onMessageMore?.(item.id, item);
              setShowClearChat(true);
            }}
            className="clear-chat-button"
          >
            Clear Chat
          </Button>
        </div>
      )}

      <div
        ref={messagesRef}
        className={`table-chat-messages ${
          groupedItems.length === 0 && !hasMore ? "empty-state-container" : ""
        }`}
      >
        {/* Infinite scroll trigger at the top for loading older messages */}
        {hasMore && (
          <div ref={loadMoreRef} className="infinite-scroll-trigger">
            {isLoadingMore ? (
              <div className="infinite-scroll-loading">
                <Loader size="medium" />
              </div>
            ) : (
              <div className="infinite-scroll-placeholder">
                {/* This element will trigger the intersection observer */}
              </div>
            )}
          </div>
        )}

        {isSearchLoading ? (
          <div className="table-chat-loading-state">
            <ChatMessageListSkeleton messageCount={4} />
          </div>
        ) : groupedItems.length === 0 && !hasMore ? (
          <div className="table-chat-empty-state">
            {isSearchActive ? (
              <EmptyContainer
                title={`No messages found for "${searchQuery}"`}
                subTitle={"Try searching for a different keyword."}
              />
            ) : (
              <>
                <EmptyContainer
                  title={"Haven't started the conversation yet!"}
                  subTitle={
                    "Start the conversation by adding members to the chat."
                  }
                />
                <Button
                  className="add_member_btn"
                  // icon={<React.Memo fontSize="small" />}
                  iconPlacement="right"
                  size="large"
                  type="default"
                  variant="secondary"
                  onClick={() => setShowAddMembers(true)}
                  disabled={showAddMembersLoading}
                >
                  {showAddMembersLoading ? "Adding..." : "Add members"}
                </Button>
              </>
            )}
          </div>
        ) : (
          groupedItems.map((item) => {
            if (item.type === "date-separator") {
              return (
                <DateSeparator
                  key={item.id}
                  date={item.date}
                  format="relative"
                />
              );
            }

            return (
              <div
                key={item.id}
                className="message-wrapper"
                data-message-id={item.id}
              >
                <ChatMessage
                  messageId={item.id}
                  author={item.author}
                  authorName={item.authorName}
                  authorAvatar={item.authorAvatar}
                  content={item.content}
                  timestamp={item.timestamp}
                  isHighlighted={highlightedMessageId === item.id}
                  highlightColor={highlightColor}
                  // Check if this message belongs to the current user
                  isUser={
                    currentUserId
                      ? item.senderId === currentUserId ||
                        item.otherProps?.sender_id === currentUserId ||
                        item.senderId === String(currentUserId) ||
                        item.otherProps?.sender_id === String(currentUserId) ||
                        item.author === "user"
                      : item.author === "user"
                  }
                  showActions={
                    messageConfig.showActions ?? item.showActions !== false
                  }
                  onReply={() => {
                    handleReply(item.id);
                    onMessageReply?.(item.id, chatId);
                  }}
                  onBookmark={() => {
                    handleBookmark(item.id);
                    onMessageBookmark?.(item.id, chatId);
                  }}
                  onPin={async (pinned) => {
                    return await handlePin(item.id, pinned, chatId, item);
                  }}
                  pinned={item.isPinned}
                  onMore={() => {
                    handleMore(item.id);
                    onMessageMore?.(item.id, chatId);
                  }}
                  onThreadClick={() => {
                    onThreadClick?.(item.id, chatId);
                    messageConfig?.onThreadClick?.(item.id, chatId);
                  }}
                  priority={item.priority}
                  type={item.type}
                  onEdit={() => handleEditMessage(item)}
                  onMessageDelete={handleMessageDelete}
                  onRefetchMessages={async () => {
                    // No need to refetch - the message is marked as deleted in local state
                    return messages;
                  }}
                  edited={item.edited || false}
                  deleted={item.deleted || item.otherProps?.deleted || false}
                  isThreadIconVisible={messageConfig?.isThreadIconVisible}
                  isPinChatIconvisible={messageConfig?.isPinChatIconVisible}
                />

                {/* {item.showReplyBadge  && (
                  <ReplyBadge
                    text={item.replyText}
                    action={item.actionText}
                    onReplyClick={() =>
                      handleReply(
                        item.id,
                        chatId,
                      )
                    }
                    onActionClick={() =>
                      console.log("Action clicked for", item.id)
                    }
                  />
                )} */}
              </div>
            );
          })
        )}

        <Modal
          className="test-modal add_members_modal"
          open={showAddMembers}
          footerOptions={<div>Footer Options</div>}
          onClose={() => {
            setShowAddMembers(false);
          }}
          onPrimaryButtonClick={saveMembersInChat}
          onSecondaryButtonClick={() => setShowAddMembers(false)}
          primaryButtonLabel={showAddMembersLoading ? "Adding..." : "Add"}
          primaryButtonProps={{
            disabled: !addMembers?.length > 0 || showAddMembersLoading,
          }}
          secondaryButtonLabel="Cancel"
          size="small"
          title="Add members"
          loading={showAddMembersLoading}
        >
          <React.Fragment key=".0">
            {/* Search Input */}
            <div className="modal-header-search-input-container">
              <Input
                placeholder="Search members..."
                value={memberSearchQuery}
                onChange={(e) => handleMemberSearch(e.target.value)}
                className="modal-header-search-input"
                leftIcon={
                  <img
                    src={SearchIcon}
                    alt="search"
                    className="menu-header-search-icon"
                  />
                }
              />
            </div>

            {memberList?.length > 0 ? (
              filteredMemberList?.length > 0 ? (
                <ul style={{ listStyle: "none", padding: 0, margin: 0 }}>
                  {filteredMemberList.map((user, index) => (
                    <li
                      key={user.id || index}
                      style={{
                        display: "flex",
                        alignItems: "center",
                        gap: "10px",
                        marginBottom: "8px", //
                      }}
                    >
                      <Checkbox
                        checked={addMembers?.includes(user?.value)}
                        defaultChecked
                        onChange={() => {
                          addInChat(user?.value);
                        }}
                        variant="default"
                      />
                      <Avatar
                        label={user?.label}
                        size="small"
                        src="static/media/avatar_sample.b13b667a.jpeg"
                        type="withoutPicture"
                      />
                      <span>{user?.label}</span>
                    </li>
                  ))}
                </ul>
              ) : (
                <div
                  style={{
                    textAlign: "center",
                    padding: "20px",
                    color: "#666",
                    fontSize: "14px",
                  }}
                >
                  No members found for "{memberSearchQuery}"
                </div>
              )
            ) : (
              "Loading..."
            )}
          </React.Fragment>
        </Modal>

        {/* Show error if infinite scroll fails */}
        {infiniteScrollError && (
          <div className="infinite-scroll-error">
            <p>Failed to load older messages. Please try again.</p>
            <Button
              variant="text"
              size="small"
              onClick={() => window.location.reload()}
            >
              Retry
            </Button>
          </div>
        )}
      </div>
      {chatId ? (
        <ChatInput
          placeholder={placeholder}
          value={inputValue}
          onChange={setInputValue}
          onSend={handleSend}
          onAttach={onAttachFile}
          onImageUpload={onImageUpload}
          onEmojiClick={onEmojiClick}
          showFormatting={showFormatting}
          showQuickAction={inputChatConfig?.inputConfig?.showQuickAction}
          quickActionLabel={inputChatConfig?.inputConfig?.quickActionLabel}
          maxLength={maxLength}
          messageConfig={messageConfig}
          isEditMode={isEditMode}
          editingMessage={editingMessage}
          onCancelEdit={exitEditMode}
          chatId={chatId}
        />
      ) : null}
      <Prompt
        handleClose={() => {
          setShowClearChat(false);
        }}
        isOpen={showClearChat}
        onPrimaryButtonClick={handleAllMessagesDelete}
        onSecondaryButtonClick={() => {
          setShowClearChat(false);
        }}
        primaryButtonLabel={isClearChatLoading ? "Clearing..." : "Clear"}
        secondaryButtonLabel="Cancel"
        title="Are you sure ?"
        variant="error"
      >
        This will permanently delete all messages in this conversation.
      </Prompt>
    </div>
  );
};

export default TableChatRightSection;
